Raf*_*ael 20 php methods class exists
因此,method_exists()需要一个对象来查看方法是否存在.但是我想知道一个方法是否存在于同一个类中.
我有一个处理一些信息的方法,并且可以接收一个操作,该方法运行一个方法来进一步处理该信息.我想在调用之前检查方法是否存在.我怎样才能实现它?
例:
class Foo{
public function bar($info, $action = null){
//Process Info
$this->$action();
}
}
Run Code Online (Sandbox Code Playgroud)
Raj*_*aul 43
你可以这样做:
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();
Run Code Online (Sandbox Code Playgroud)
Flo*_*lus 10
使用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()
Run Code Online (Sandbox Code Playgroud)
method_exists()接受类名称或对象实例作为参数。所以你可以检查一下$this
http://php.net/manual/zh/function.method-exists.php
参数 ¶
对象 对象实例或类名
method_name 方法名称
小智 5
我认为最好的方法是使用 __call 魔术方法。
public function __call($name, $arguments)
{
throw new Exception("Method {$name} is not supported.");
}
Run Code Online (Sandbox Code Playgroud)
是的,您可以使用 method_exists($this ...) 但这是 PHP 的内部方式。