检查同一个类中是否存在多个方法


Check if multiple methods exists in same Class?

是否有一种方法来验证在同一个类中是否存在多个方法?

class A{
    function method_a(){}
    function method_b(){}
}
if ( (int)method_exists(new A(), 'a', 'b') ){
    echo "Method a & b exist";
}

我可能会在这里使用interface:

interface Foo {
  function a();
  function b();
}

…然后,在客户机代码中:

if (A instanceof Foo) {
   // it just has to have both a() and b() implemented
}

我认为这更清楚地表明你的真实意图,而不仅仅是检查方法的存在

使用get_class_methods:

class A {
  function foo() {
  }
  function bar() {
  }
}
if (in_array("foo", get_class_methods("A")))
  echo "foo in A, ";
if (in_array("bar", get_class_methods("A")))
  echo "bar in A, ";
if (in_array("baz", get_class_methods("A")))
  echo "baz in A, ";
// output: "foo in a, bar in a, "

你可以在这里摆弄:http://codepad.org/ofEx4FER

不要认为存在这样的功能,但是您可以尝试get_class_methods并比较类方法和您的方法的数组,例如:

$tested_methods = array('a', 'b', 'c');
if (sizeof($tested_methods) == sizeof(array_intersect($tested_methods, get_class_methods("class_name"))))
    echo 'Methods', implode(', ', $tested_methods), ' exist in class';

您需要单独检查每个方法:

$a = new A();
if(method_exists($a, 'method_a'))...
if(method_exists($a, 'method_b'))...

不能在一个函数调用中检查多个方法