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

时间:2013-06-01 18:24:45

标签: php class

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

class A{
    function method_a(){}
    function method_b(){}
}

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

4 个答案:

答案 0 :(得分:3)

我可能在这里使用了界面:

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

...然后,在客户端代码中:

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

我认为这更清楚地表明了你真正的意图,然后只是检查方法的存在。

答案 1 :(得分:2)

使用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

答案 2 :(得分:1)

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

$a = new A();

if(method_exists($a, 'method_a'))...
if(method_exists($a, 'method_b'))...

您无法在一个函数调用中检查多个方法

答案 3 :(得分:1)

不要认为这样的功能存在,但你可以尝试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';