How do I get a PHP class constructor to call its parent's parent's constructor?

前端 未结 15 1444
滥情空心
滥情空心 2020-11-28 21:38

I need to have a class constructor in PHP call its parent\'s parent\'s (grandparent?) constructor without calling the parent constructor.

//         


        
15条回答
  •  忘掉有多难
    2020-11-28 22:02

    There's an easier solution for this, but it requires that you know exactly how much inheritance your current class has gone through. Fortunately, get_parent_class()'s arguments allow your class array member to be the class name as a string as well as an instance itself.

    Bear in mind that this also inherently relies on calling a class' __construct() method statically, though within the instanced scope of an inheriting object the difference in this particular case is negligible (ah, PHP).

    Consider the following:

    class Foo {
        var $f = 'bad (Foo)';
    
        function __construct() {
            $this->f = 'Good!';
        }
    }
    
    class Bar extends Foo {
        var $f = 'bad (Bar)';
    }
    
    class FooBar extends Bar {
        var $f = 'bad (FooBar)';
    
        function __construct() {
            # FooBar constructor logic here
            call_user_func(array(get_parent_class(get_parent_class($this)), '__construct'));
        }
    }
    
    $foo = new FooBar();
    echo $foo->f; #=> 'Good!'
    

    Again, this isn't a viable solution for a situation where you have no idea how much inheritance has taken place, due to the limitations of debug_backtrace(), but in controlled circumstances, it works as intended.

提交回复
热议问题