php类知识点滴---魔术方法,系统在特定时机触发的方法

  • __get()获取私有或受保护属性时调用的方法
<?php
class coach
{
    private $chairfit = "徐晓冬";
    public function __construct()
    {
        echo "欢迎来到~必图拳馆训练~";
    }
    public function __get($chairfit)
    {
        echo $chairfit;//只打印属性名
    }
}
class xxd extends coach
{
   public function __construct()
   {
       echo "像个男人一样去战斗!"."\n";
   }

}
$cj = new xxd();
$cj ->chairfit;
?>
输出结果:

像个男人一样去战斗!               #构造方法调用结果
chairfit                                  #继承自父类的__get()方法



#这样可以访问父类私有属性的值
<?php
class coach
{
private $chairfit = "徐晓冬";
public function __construct()
{
echo "欢迎来到~必图拳馆训练~";
}
public function __get($chairfit)
{
if ($chairfit=='chairfit')
{
return $this->chairfit;
}
}
}
class xxd extends coach
{
public function __construct()
{
echo "像个男人一样去战斗!"."\n";
}

}
$cj = new cj();
print($cj ->chairfit);
?>
输出结果:

像个男人一样去战斗!         #构造方法调用结果
徐晓冬        #通过父类的__get()方法访问父类私有属性

 

猜你喜欢

转载自www.cnblogs.com/saintdingspage/p/10958937.html