开发者

Propagating a function to parents

开发者 https://www.devze.com 2023-02-06 10:14 出处:网络
I have a PHP object that consists of a set of classes. For sake of simplicity lets call it an object of class C that extends class B which in its turn extends class A. At some point in my code I want

I have a PHP object that consists of a set of classes. For sake of simplicity lets call it an object of class C that extends class B which in its turn extends class A. At some point in my code I want to clean up the object by calling its doCleanup() function which it inherits from interface I:

interface I { public function doCleanup(); }

class A implements I { ... }
class B extends A { ... }
class C extends B implements I { ... }

In the doCleanup function in class C I want to also execute any cleanup function in my parent classes (in this case, the doCleanup() in class A). However, for some objects I am not sure whether any of the parent classes actually implement interface I, so I am not sure whether I can simpley call parent::doCleanup().

开发者_StackOverflowMy question therefore is if there is a way to check whether any of my ancestors implement the interface for example by using some sort of instanceof call?


You can do this nicely with get_parent_class and is_subclass_of (which works for interfaces as well as parent classes):

<?php

interface I {
    public function doCleanup();
}

class A implements I {
    public function doCleanup() {
        echo "done cleanup\n";
    }
}

class B extends A {}

class C extends B implements I {
    public function doCleanup() {
        if (is_subclass_of(get_parent_class($this), 'I')) {
            parent::doCleanup();
        }
    }
}

$c = new C;
$c->doCleanup(); // outputs "done cleanup"


Since class C extends B, and B extends A, and A is required to implement doCleanup, then logically you can call parent::doCleanup() in C and it will work. If B does not implement it, it will be passed up to A, which must implement it. More accurately, B will run it, using A's implementation.

If you didn't know whether A implemented I or not, then it wouldn't necessarily be your responsibility to call it. If it were library code, for example, docs might tell you what you should do.

0

精彩评论

暂无评论...
验证码 换一张
取 消