时间:2021-07-01 10:21:17 帮助过:22人阅读

PHP有一个魔术方法,叫做__call。当你调用一个不存在的方法时,这个方法会被自动调用。
这时,我们就有机会将调用重定向到一个存在的方法。继承多个父类的子类,寻找方法的过程一般是这样的:(推荐学习:PHP视频教程)
本身的方法 -> 父类1的方法 -> 父类2的方法...
模拟过程大致是这样:将各个父类实例化,然后作为子类的属性。这些父类提供一些公有的方法。当子类拥有某方法时,__call()函数不会被调用。这相当于“覆盖”了父类的方法。
当调用了不存在的方法时,通过__call()方法依次从父类中寻找可以调用的方法。虽然这不是完备的多继承,但可以帮助我们解决问题。
<?php
class Parent1 {
function method1() {}
function method2() {}
}
class Parent2 {
function method3() {}
function method4() {}
}
class Child {
protected $_parents = array();
public function Child(array $parents=array()) {
$_parents = $parents;
}
public function __call($method, $args) {
// 从“父类"中查找方法
foreach ($this->_parents as $p) {
if (is_callable(array($p, $method))) {
return call_user_func_array(array($p, $method), $args);
}
}
// 恢复默认的行为,会引发一个方法不存在的致命错误
return call_user_func_array(array($this, $method), $args);
}
}
$obj = new Child(array(new Parent1(), new Parent2()));
$obj->method1();
$obj->method3();这里没有涉及属性的继承,但实现起来并不困难。可以通过__set()和__get()魔术方法来模拟属性的继承。
以上就是php是单继承吗的详细内容,更多请关注Gxl网其它相关文章!