__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个静态方法。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号