开发者

PHP: This and Self [duplicate]

开发者 https://www.devze.com 2023-01-28 19:52 出处:网络
This question already has answers here: 开发者_运维百科 Closed 12 years ago. Possible Duplicate: PHP: self vs this and
This question already has answers here: 开发者_运维百科 Closed 12 years ago.

Possible Duplicate:

PHP: self vs this and When to use self over $this

What's the difference between $this and self::

example:

class Object{
   public $property;
   function doSomething(){
        // This
        $something = $this->property;
        // Self
        $something = self::property;
        ...code...
   }
}


$this refers to the instance of the object, while self returns to the class itself. When using static calls, you refer to self because you are not-required to have an instance of a class (i.e. $this).


$this references the object, in which the code appears, self is the class. You call "usual" methods and properties with $this from within any method and you call static methods and properties with self

class A {
    public static $staticVar = 'abc';
    public $var = 'xyz';
    public function doSomething () {
        echo self::$staticVar;
        echo $this->var;
    }
}

Your "Self"-example is invalid anyway.


Taken from here

Link: http://www.phpbuilder.com/board/showthread.php?t=10354489:

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.

Answered by John Millikin here

0

精彩评论

暂无评论...
验证码 换一张
取 消