让一个类始终返回 true 对于方法存在


Have a class always return true for method exists

我有一个类,我想在调用 method_exists() 等时返回 true,以便我可以通过 __call() 处理它。

我偶然发现了这个链接,该链接讨论了行为的删除和__call()https://bugs.php.net/bug.php?id=32429

希望这是有道理的。谢谢。

这是针对我不够清楚的评论。

class MyClass {
  public function __call($method, $args) {
    if($method === 'something') {
      // do something
    }
  }
}

然后其他地方有

$my_class = new MyClass();
if(method_exists($my_class, 'something')) {
  // do something
  // But does not because method exists returns false
  // I would like it to return true if possible
}

有什么我不明白的复杂之处吗?

method_exists不会检测到__call魔法处理的未定义方法,因为您传递它的未定义方法实际上不存在。如果是这样,它将被视为一个错误,如您的问题中所链接的那样。

执行此操作的唯一方法(没有像runkit这样的PECL扩展或修改PHP源代码)是使用一些命名空间黑魔法来覆盖method_exists的行为:

namespace Foo;
function method_exists($object, $method) {
    return 'method_exists($object, '__call') ?: 
           'method_exists($object, $method);
}
class Bar {
    public function __call($n, $a) { }
}
class Baz { }
var_dump(method_exists('Foo'Baz', 'hello')); // false
var_dump(method_exists('Foo'Bar', 'hello')); // true

我不会推荐它,但是嘿,你要求它。