博客列表 >PHP面向对象编程:__call()实现跨类调用方法

PHP面向对象编程:__call()实现跨类调用方法

hanyufeng的博客
hanyufeng的博客原创
2018年01月13日 17:13:111709浏览

__call()方法是PHP的魔术方法之一,当对象调用一个不存在或限制访问的类方法时,程序会自动调用__call()方法。

在__call()方法中使用call_user_func_array()函数调用其它类的方法,就实现了方法的跨类调用。

例如:

class User{
    private $name;
    private $grade;
    private $class;
 
    //__get()方法获取属性值
    public function __get($propertyName){
        return $this->$propertyName;
    }
 
    //__set()方法设置属性值
    public function __set($propertyName,$value){
        $this->$propertyName = $value;
    }
}
 
class Student extends User
{
    protected $score;//定义子类的变量
 
    public function __call($name, $arguments)
    {
        //跨类调用方法
        return call_user_func_array([(new Teacher),$name],$arguments);
    }
}
 
class Teacher extends User
{
    protected $phoneNum;//手机号码
    protected $studentCount;//学生数
    protected static $classCount;//班级数
 
    public function __construct()
    {
        $this->studentCount = 60;
        self::$classCount = 3;
    }
 
    public function getStudentCount(){
        return $this->studentCount;
    }
 
    public static function getClassCount(){
        return self::$classCount; //静态方法只能调用静态对象
    }
}
 
$stu = new Student();
echo $stu->getStudentCount();
echo '<br>';
echo $stu->getClassCount();

运行效果:

60
3

$stu 对象跨类调用了 Teacher类的2个方法,包括1个静态方法。

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议