The Project I'm working on contains something like a wrapper for call_user_func(_array) which does some checks before execution. One of those checks is method_exists (In Case the supplied first argument is an instance of a class and the second is a method name) The other is_callable. The function will throw an exception if one of those checks fails.
My Code contains an array with function names (setFoo, setBar, etc.) and the php magic function for overloading (__call) which handles setting, replacing and deletion of certain variables (better certain array elements).
The Problem: method_exists will return false if the function is not defined.
Do I have any chance to get a true if the __call function does proper handling of the request?
When you call a method on an object of the Str class and that method doesn't exist e.g., length() , PHP will invoke the __call() method. The __call() method will raise a BadMethodCallException if the method is not supported. Otherwise, it'll add the string to the argument list before calling the corresponding function.
Magic methods in PHP are special methods that are aimed to perform certain tasks. These methods are named with double underscore (__) as prefix. All these function names are reserved and can't be used for any purpose other than associated magical functionality. Magical method in a class must be declared public.
PHP Magic Methods __sleep() and __wakeup()__sleep is supposed to return an array of the names of all variables of an object that should be serialized. __wakeup in turn will be executed by unserialize if it is present in class.
Use the PHP method_exists() function to check if an object or a class has a specified method.
__call
handles calls to methods that don't exist. method_exists
is an introspection method that checks the existence of a method.
How can __call
be determined to handle a method? I think you have to throw an exception manually in __call
if doesn't handle your request and catch the exception in the code that would otherwise use method_exists
. BadMethodCallException
exists for this purpose.
Have a look at is_callable()
.
But no, if the __call()
method only handles some names, then you would need some other way of checking if the call will succeed.
Might I suggest a interface with the method canCall($function)
, or something? Then check if the class implements the interface. If it doesn't, just use is_callable()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With