在PHP中,可以判断parent是否显式调用了一个方法::

时间:2014-08-13 16:37:40

标签: php oop

是否可以判断父类中的方法是否由parent ::显式调用,而不是自动调用,因为子类不包含被调用的方法?

1 个答案:

答案 0 :(得分:2)

好吧,我不确定你能轻易搞定。 无论如何,我认为你可以按照这种方式,如果你需要解决方法:

示例1:

class Par

{
    function printit($which = false)
    {
        // when you call this method, based on variable it tells how it was called
        if ($which) {
            echo "called with parent \n";
        } else {
            echo "called with this \n";
        }
    }
}

class Chi extends Par

{
    function callParent()
    {
        parent::printit(TRUE);
    }

    function callFunction()
    {
        $this->printit(FALSE);
    }
}

$chi = new Chi();
$chi->callParent();
$chi->callFunction();

示例2:

class Par

{
    function printit()
    {
        // get all functions in child class
        $child_methods = array_diff(get_class_methods("Chi") , get_class_methods("Par"));
        // if the function there is in child class, probably it was called from there
        if (in_array(__FUNCTION__, $child_methods)) {
            echo "called with child \n";
        } else {
            echo "called with parent \n";
        }
    }
}

class Chi extends Par

{
    function callParent()
    {
        parent::printit();
    }

    function callFunction()
    {
        $this->printit();
    }
}

$chi = new Chi();
$chi->callParent();
$chi->callFunction();
相关问题