Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP __call vs method_exists

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?

like image 519
neo Avatar asked Oct 01 '09 18:10

neo


People also ask

What is __ call () in PHP?

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.

What are PHP magic methods?

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.

What's the special meaning of __ sleep and __ wakeup?

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.

How do you check if a class has a method PHP?

Use the PHP method_exists() function to check if an object or a class has a specified method.


2 Answers

__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.

like image 79
JF Simon Avatar answered Oct 12 '22 13:10

JF Simon


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().

like image 23
gnud Avatar answered Oct 12 '22 14:10

gnud