PHP 面向对象基础:访问成员 $this
什么是 $this
?
如果想在类内部使用本类的属性或者方法时,可以使用伪变量 $this
, 它是指向当前对象的指针。
如何使用 $this
?
声明一个类
class Parents
{
public $parents = 'Parents';
private $money = '100,000';
function printThis()
{
if (isset($this)) {
echo '$this (' . get_class() . ') is defined.' . '<br />';
} else {
echo '$this is not defined.' . '<br />';
}
}
public function talk()
{
echo $this->parents . ' are talking.' . '<br />';
}
public function showMoney()
{
echo $this->parents . ' deposit ¥' . $this->money . ' in bank.' . '<br />';
}
}
实例化这个类
$parents = new Parents();
通过调用 printThis
方法显示 $this
就是指代类 Parents
。
$parents->printThis(); // $this (Parents) is defined.
还可以通过 $this
调用类的私有属性。
$parents->showMoney(); // Parents deposit ¥100,000 in bank.