小编jav*_*xin的帖子

如何确定方法是继承的、重新定义的还是新的 (PHP)

我想要一个函数来检查一个类是否定义了某个方法,类似于,但是如果提到的方法存在并且它是在 obj 类本身中定义的,而不是继承的,那么method_exists类似的函数将返回 true。method_defined($obj, 'method_name');对于未继承的新方法,它应该返回 true (这可以很好地检查方法是否在父类中定义,例如method_exists($obj, $method) && !method_exists(get_parent_class($obj), $method)),对于重新定义的继承方法(不知道如何执行)也应该返回 true,但返回false 对于未重新定义的继承方法(也不知道)。

示例代码:

<?php
class base
{
    var $x = 'x';
    function doit()
    {
        return $this->x;
    }
}

class a extends base
{
    function doit()
    {
        return 'a';
    }
}

class b extends base
{
    var $x = 'b';
}

class c extends base
{
}

function method_defined($obj, $method)
{
    return method_exists($obj, $method); // this is the question
}

function info($obj)
{
    echo …
Run Code Online (Sandbox Code Playgroud)

php methods inheritance

2
推荐指数
1
解决办法
472
查看次数

标签 统计

inheritance ×1

methods ×1

php ×1