Blogger Information
Blog 33
fans 0
comment 2
visits 41929
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PHP面向对象编程:__call()实现跨类调用方法
hanyufeng的博客
Original
1708 people have browsed it

__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个静态方法。

Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!