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.
class Demo
{
private static $name;
private $age;
public function __construct($name, $age)
{
self::$name = $name;
$this->age=$age;
}
public function show()
{
echo "Name : ", self::$name, "<br/>"; //Accessing by self
echo "Name : ", Demo::$name, "<br/>"; //Accessing by class name
echo "Age : ", $this->age, "<br/>";
}
}
$demo = new Demo("Tiny", 13);
$demo->show();
This produces the following output.
Name : Tiny
Name : Tiny
Age : 13
What is the difference between self::$name
and Demo::$name
in the preceding snippet?
class Person1
{
private $name;
private $address;
public function __construct($name,$address)
{
$this->name = $name;
$this->address = $address;
}
public function show()
{
echo "Name : ", $this->name, "<br/>";
echo "Address : ", $this->address, "<br/>"; //Accessing by this
}
}
$p1=new Person1("xxx", "yyy");
$p1->show();
class Person2
{
private $name;
private $address;
public function __construct($name,$address)
{
self::$name = $name;
self::$address = $address;
}
public function show()
{
echo "Name : ", self::$name, "<br/>";
echo "Address : ", self::$address, "<br/>"; //Accessing by self
}
}
$p2=new Person1("xxx", "yyy");
$p2->show();
Preceding two classes Person1
and Person2
produce the same output as follows.
Name : xxx
Address : yyy
What is the difference between (as in the Preson1
class, the show()
method)
$this->name;
$this->address;
and (as in the Preson2
class, the show()
method)
self::$name;
self::$address;
in this context?