'Have a class always return true for method exists
I have a class that I would like to return true when method_exists() etc is called on it so that I can process it via __call().
I stumbled upon this link that talks about the removal of the behavior and __call() https://bugs.php.net/bug.php?id=32429
Hopefully that makes sense. Thanks.
This is for a comment that I was not clear enough.
class MyClass {
public function __call($method, $args) {
if($method === 'something') {
// do something
}
}
}
Then somewhere else there is
$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
}
Is there something complicated about that I'm not understanding?
Solution 1:[1]
method_exists will not detect undefined-methods which the __call magic handles, because the undefined method you pass it actually does not exist. It would be considered a bug if it did, as linked in your question.
The only way to do this (without a PECL extension like runkit or modifying the PHP source), is to use some namespace black magic to override the behavior of 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
I wouldn't recommend it, but hey, you asked for it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Top-Master |
