Capture "Call member function foo () for non-objects"

Is there any way to catch Call to a member function foo() on a non-object in PHP? It doesn't sound so serious (as fatal errors occur), but the shutdown function doesn't seem to be called at all (PHP 5.3, Debian).

Update:

How to prevent such errors is really wrong. Of course, you need to check the null value when this is an expected possibility, but clogging each link to the function of an object element with error checking code will lead to a bloated and unreadable code. Hunting for a random error based on logs is fine - the problem is that logs are not very useful for fatal errors. Using the shutdown function will solve this well, but I cannot get it to work with this particular type of error; which seems strange to me because it is not a mistake that would leave the PHP interpreter in a particularly dirty state.

+4
source share
2 answers

Hope this sounds silly, but you have to make sure you know what you're working with. Use instanceof or is_object where you need to - or fix the source of the problem - why is this variable not an object in the first place?

0
source

I suggest just making sure that this is an object. Using methods / functions, you can use type hints

 public function x (myClass $object) { $object->foo(); } 

otherwise you can use is_object() . At the end, such a message sounds as if your application has a bug that should be fixed before release, or - if such a situation may arise by design - check the type ( is_object() (see above) or !is_null($obj) or something like that) before trying to call something that does not exist.

0
source

Source: https://habr.com/ru/post/1383846/


All Articles