所以,method_exists()
需要一个对象来查看方法是否存在。但是我想知道从同一类中是否存在这个方法。
我有一个处理信息并且可以接收操作的方法,该操作会运行一个方法来进一步处理该信息。我想在调用它之前检查该方法是否存在。我该如何实现?
例如:
class Foo{
public function bar($info, $action = null){
//Process Info
$this->$action();
}
}
所以,method_exists()
需要一个对象来查看方法是否存在。但是我想知道从同一类中是否存在这个方法。
我有一个处理信息并且可以接收操作的方法,该操作会运行一个方法来进一步处理该信息。我想在调用它之前检查该方法是否存在。我该如何实现?
例如:
class Foo{
public function bar($info, $action = null){
//Process Info
$this->$action();
}
}
你可以像这样做:
class A{
public function foo(){
echo "foo";
}
public function bar(){
if(method_exists($this, 'foo')){
echo "method exists";
}else{
echo "method does not exist";
}
}
}
$obj = new A;
$obj->bar();
使用method_exists
是正确的。但是,如果你想符合“接口隔离原则”,你可以创建一个接口来执行内省,像这样:
class A
{
public function doA()
{
if ($this instanceof X) {
$this->doX();
}
// statement
}
}
interface X
{
public function doX();
}
class B extends A implements X
{
public function doX()
{
// statement
}
}
$a = new A();
$a->doA();
// Does A::doA() only
$b = new B();
$b->doA();
// Does B::doX(), then remainder of A::doA()
method_exists()
接受类名或对象实例作为参数。所以你可以检查$this
。
http://php.net/manual/en/function.method-exists.php
参数 ¶
object 对象实例或类名
method_name 方法名
public function __call($name, $arguments)
{
throw new Exception("Method {$name} is not supported.");
}
是的,你可以使用method_exists($this ...),但这是PHP内部的方法。