使用 $this 来引用当前对象。使用 self 来引用当前类。换句话说,对非静态成员使用 $this->member,对静态成员使用 self::$member。
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();
这会产生以下输出。
Name : Tiny
Name : Tiny
Age : 13
self::$name
和Demo::$name
前面的代码片段有什么区别?
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();
前面两个类Person1
并Person2
产生相同的输出,如下所示。
Name : xxx
Address : yyy
Preson1
(如在类中,show()
方法中)有什么区别
$this->name;
$this->address;
和(如在Preson2
类中,show()
方法)
self::$name;
self::$address;
在这种情况下?