greenoldman
greenoldman

Reputation: 21052

Is it possible to intercept the call to non-existing function?

PHP has its magical methods __call and __callStatic which allow to intercept the calls to non-existing methods. I am looking for a way to intercept the call to non-existing function (the one that sits inside a namespace, not a type).

Is it possible to do (PHP7)?

For a moment I considered putting functions inside proxy class, but namespace can span over several files, and if I am not mistaken, PHP does not have partial classes, thus this approach is of no use.

Update: multiple files per namespace problem.

Let's say I have file A.php and B.php, both with the same namespace, say Text. Consider putting all the functions to proxy classes. And now I have file C.php and I have call Text\indexOf(...). However I don't know if this is Text\proxyA::indexOf or Text\proxyB::indexOf because all information I have is name of the namespace -- Text -- and function name. So from caller side I am toasted.

Upvotes: 5

Views: 878

Answers (2)

nkkollaw
nkkollaw

Reputation: 2040

With PHP7+ you can catch calls to undefined functions:

try {
    not_exist();
} catch (\Error $e) {
    echo 'ERROR: ' . $e->getMessage();
}

You can then use set_exception_handler to catch that without it being in a try/catch block:

set_exception_handler(function($e) {
    echo '<BR>ERROR: ' . $e->getMessage();
});

not_exist();

Note that you need to use set_exception_handler and not set_error_handler.

Upvotes: 3

rjdown
rjdown

Reputation: 9227

As of PHP7 you can catch undefined function calls:

try {
    idontexist();
} catch (\Error $e) {
    echo $e->getMessage();
}

There is no way to use this in the same way as __call, except of course through a custom error handler.

Demo: https://3v4l.org/j4WRB

Upvotes: 2

Related Questions