What is difference between this and self in php?

Where's the difference between self and $this-> in a PHP class or PHP method?

Example:

I've seen this code recently.

public static function getInstance[] {

    if [!self::$instance] {
        self::$instance = new PDO["mysql:host='localhost';dbname='animals'", 'username', 'password'];;
        self::$instance-> setAttribute[PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION];
    }
    return self::$instance;
}

But I remember that $this-> refers to the current instance [object] of a class [might also be wrong]. However, what's the difference?

asked Dec 22, 2009 at 18:37

3

$this refers to the instance of the class, that is correct. However, there is also something called static state, which is the same for all instances of that class. self:: is the accessor for those attributes and functions.

Also, you cannot normally access an instance member from a static method. Meaning, you cannot do

static function something[$x] {
  $this->that = $x;
}

because the static method would not know which instance you are referring to.

answered Dec 22, 2009 at 18:40

Tor ValamoTor Valamo

32.5k11 gold badges71 silver badges81 bronze badges

3

$this refers to the current object, self refers to the current class. The class is the blueprint of the object. So you define a class, but you construct objects.

So in other words, use self for static and this for non-static members or methods.

mickmackusa

39k11 gold badges76 silver badges112 bronze badges

answered Dec 22, 2009 at 18:40

YacobyYacoby

53.3k13 gold badges111 silver badges119 bronze badges

self is used at the class-level scope whereas $this is used at the instance-level scope.

answered Dec 22, 2009 at 18:39

jldupontjldupont

89.6k56 gold badges195 silver badges310 bronze badges

  1. this-> can't access static method or static attribute , we use self to access them.
  2. $this-> when dealing with extended class will refer to the current scope that u extended , self will always refer to the parent class because its doesn't need instance to access class method or attr its access the class directly.

Chủ Đề