Home  >  Article  >  Backend Development  >  Is php single inheritance?

Is php single inheritance?

(*-*)浩
(*-*)浩Original
2019-09-29 10:45:532631browse

PHP does not have multiple inheritance features. Even in a programming language that supports multiple inheritance, we rarely use this feature. In the opinion of most people, multiple inheritance is not a good design method. If you want to add additional features to a class, you don't necessarily need to use inheritance. Here I provide a method to simulate multiple inheritance for reference.

Is php single inheritance?

PHP has a magic method called __call. When you call a method that doesn't exist, this method will be called automatically.

At this time, we have the opportunity to redirect the call to an existing method. For subclasses that inherit multiple parent classes, the process of finding methods is generally as follows: (Recommended learning: PHP Video Tutorial)

本身的方法 -> 父类1的方法 -> 父类2的方法...

The simulation process is roughly as follows: add each parent class instance ization, and then as an attribute of the subclass. These parent classes provide some public methods. When a subclass owns a method, the __call() function will not be called. This is equivalent to "overriding" the method of the parent class.

When a method that does not exist is called, looks for methods that can be called from the parent class through the __call() method. Although this is not complete multiple inheritance, it can help us solve the problem.

<?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();

There is no inheritance of properties involved, but it is not difficult to implement. Property inheritance can be simulated through the __set() and __get() magic methods.

The above is the detailed content of Is php single inheritance?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn