Question

the following example will for sure output an error:

$myVar = "hello";
$var->exeptionForSure();

==> Fatal error: Call to a member function exeptionForSure() on a non-object in..

Is there a way I can simulate/implement the magic method __call() to also work in this kind of situations?

I would like to be able to call a function of my own if for some reason I try to access methods in non-objects.

Was it helpful?

Solution

There is no facility for this in PHP, and there probably never will be.

Any such method would have to exist globally for the duration of the PHP script (there is no class context for it to run within) and its existence would probably complicate the code a lot for such an unusual requirement.

It would also imply some slightly odd scoping rules: assuming that $non_object->method(42); was translated as magic_non_object_call($non_object, 'method', array(42)); the left-hand operand ($non_object) would have to be passed in either by value (in which case it could not be written back to) or by reference (which requires PHP to abandon "copy-on-write" memory optimisations for that variable). Note that objects are represented with an additional layer of abstraction, so that $this (and objects passed or copied "by value") actually contain a handle to the "real" object, avoiding this exact problem.

Fundamentally, the only reason you should need to do this is as a "last ditch" error handler - if your code is such that you cannot tell whether a given variable is an object or not, that is a bug. Unfortunately, this is a Fatal Error, so I don't think you can catch/handle it. (Note that it is not an Exception; very few PHP built-ins throw Exceptions.)

OTHER TIPS

This should work:

method_exists($var, 'exeptionForSure') ? $var->exeptionForSure() : fallback();

You can also define specific method for your object that will do the same as above, so you can do following:

$obj->call_func('func_name', $params);

Only objects have methods that you can invoke. In PHP, strings, numbers, etc are not objects, so you can't define, or call, methods on them.

method_exists checks if a certain method exists for a given object. But you should not call this function for non-objects.

First you should check if $var is an object or not:

if (is_object($var) && method_exists($var, 'exeptionForSure')) {
   $var->exeptionForSure();
} else {
   fallback(); 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top