Thursday, April 5, 2018
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.
Here is an example of correct usage of
$this and self for non-static and static member variables:<?php
class X {
private $non_static_member = 1;
private static $static_member = 2;
function __construct() {
echo $this->non_static_member . ' '
. self::$static_member;
}
}
new X();
?>
---------------------------------------
self points to the class in which it is written.
So, if your getInstance method is in a class name
MyClass, the following line :self::$_instance = new self();
Will do the same as :
self::$_instance = new MyClass();
---------------------------------------
If you have two classes that extend each other, you have two situations :
getInstanceis defined in the child classgetInstanceis defined in the parent class
The first situation would look like this (I've removed all non-necessary code, for this example -- you'll have to add it back to get the singleton behavior)* :
class MyParentClass {
}
class MyChildClass extends MyParentClass {
public static function getInstance() {
return new self();
}
}
$a = MyChildClass::getInstance();
var_dump($a);
Here, you'll get :
object(MyChildClass)#1 (0) { }
Which means
self means MyChildClass -- i.e. the class in which it is written.For the second situation, the code would look like this :
class MyParentClass {
public static function getInstance() {
return new self();
}
}
class MyChildClass extends MyParentClass {
}
$a = MyChildClass::getInstance();
var_dump($a);
And you'd get this kind of output :
object(MyParentClass)#1 (0) { }
Which means
self means MyParentClass -- i.e. here too, the class in which it is written.With PHP < 5.3, that "the class in which it is written" is important -- and can sometimes cause problems.
That's why PHP 5.3 introduces a new usage for the
static keyword : it can now be used exactly where we used self in those examples :class MyParentClass {
public static function getInstance() {
return new static();
}
}
class MyChildClass extends MyParentClass {
}
$a = MyChildClass::getInstance();
var_dump($a);
But, with
static instead of self, you'll now get :object(MyChildClass)#1 (0) { }
Which means that
static sort of points to the class that is used (we used MyChildClass::getInstance()), and not the one in which it is written.
Of course, the behavior of
self has not been changed, to not break existing applications -- PHP 5.3 just added a new behavior, recycling the static keyword.