1

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...
   }
}
Saqib Javed
  • 178
  • 6
  • 17
Adam Halasz
  • 55,145
  • 63
  • 144
  • 211

3 Answers3

3

$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).

Anthony Forloney
  • 87,377
  • 14
  • 113
  • 114
2

$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.

KingCrunch
  • 124,572
  • 19
  • 146
  • 171
  • Be careful with `self`. `self` refers to the most recent class in the chain which contains that method. If you have a static `$name` property in both a `ParentClass` and `ChildClass` which hold "Parent" and "Child" respectively, but `showName`, which uses `self::$name`, only exists in `ParentClass` then `$child->showName()` will return `Parent` not `Child`. – AgentConundrum Dec 05 '10 at 23:31
  • Usually its the prefered behaviour, when `self` really means "the class itself" and not any subclass. Use "Late Static Binding (`static`), which always refers to the called class instead. – KingCrunch Dec 06 '10 at 00:58
1

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

Rotimi
  • 4,710
  • 4
  • 17
  • 27
Trufa
  • 38,078
  • 41
  • 121
  • 186