[php] self、$this 區別

2019062412:00
 

Use $this to refer to the current object. Use self to refer to the current class.
In other words,
use $this->member for non-static members,
use self::$member for static members. 


範例
<?php
class X {
    private $non_static_member = 1;
    private static $static_member = 2;

    function __construct() {
    
        echo $this->non_static_member ;
        echo self::$static_member ;

        //echo self::$non_static_member ;
        //^^^不可這樣寫, 會出現錯誤: Fatal error: Uncaught Error: Access to undeclared static property..
        //self 不可存取 "非"static properth/method,但 $this 可以
        
        //echo $this->static_member;
        //^^^不可這樣寫,會出現錯誤: PHP Notice:  Accessing static property X::$static_member as non static in..
        //$this 不可存取 static properth/method
    }
    
    static function static_fun() {
        echo "static_fun()\n";
    }
    
    public function fun() {
        echo "fun()\n";
    }
    
}

$xx = new X();

$xx::static_fun();
$xx->static_fun();

//$xx::fun(); //這樣寫會出現錯誤:  PHP Deprecated:  Non-static method X::fun() should not be called statically...
$xx->fun();


https://stackoverflow.com/questions/151969/when-to-use-self-over-this