检查扩展类中是否存在方法,但父类是否存在

xia*_*kai 6 php

使用method_exists,它会检查所有方法,包括父类.

例:

class Toot {
    function Good() {}
}

class Tootsie extends Toot {
    function Bad() {}
}

function testMethodExists() {
    // true
    var_dump(method_exists('Toot', 'Good'));

    // false
    var_dump(method_exists('Toot', 'Bad'));

    // true
    var_dump(method_exists('Tootsie', 'Good'));

    // true
    var_dump(method_exists('Tootsie', 'Bad'));
}
Run Code Online (Sandbox Code Playgroud)

如何检查该方法仅存在于当前类而不是父类(即.Tootsie)?

Ela*_*ail 6

由于v.4.0.5 php有get_parent_class()方法,因此返回父类.所以你可以在没有重新选择的情况下处理它:

class A
{
    function a() { /* ... */}    
    function b() { /* ... */}    
}
class B extends A
{
    function b() { /* ... */}    
    function c() { /* ... */}    
}

function own_method($class_name, $method_name)
{    
    if (method_exists($class_name, $method_name))
    {
        $parent_class = get_parent_class($class_name);
        if ($parent_class !== false) return !method_exists($parent_class, $method_name);
        return true;
    }
    else return false;
}

var_dump(own_method('B', 'a')); // false
var_dump(own_method('B', 'b')); // false 
var_dump(own_method('B', 'c')); // true
Run Code Online (Sandbox Code Playgroud)


sle*_*ess 6

如果您需要知道该方法是否存在于给定的子类中,无论父类中是否存在,您可以这样做:

$reflectionClass = new ReflectionClass($class_name);
if ($reflectionClass->getMethod($method_name)->class == $class_name) {
    // do something
}
Run Code Online (Sandbox Code Playgroud)


小智 2

你可以使用反射

$refl = new ReflectionClass($class_name); 
   
if($refl->hasMethod($method_name)){
       //do your stuff here 
}
Run Code Online (Sandbox Code Playgroud)

了解更多信息

  • 不幸的是,这似乎也遇到了与“method_exists”相同的问题 - “父方法(无论可见性如何)也可用于 ReflectionObject。” 来自http://ca3.php.net/manual/en/reflectionclass.hasmethod.php#100660 (5认同)