Reputation: 11
In the example code:
<?php
for ($i = 1; $i <=20; $i++) {
echo $i . '<br />';
if ($i == 10) {
$haha->hoho("hehe");
}
}
?>
When $i = 10 program will show this error, Call to a member function hoho() on a non-object
because $haha is not a object and the program stops running. I want the program to handle this error and continue running to $i=20. How can I do it?
Upvotes: 1
Views: 101
Reputation:
Long answer:
There is lots of ways to do that, the first thing off the top of my head is to use set_error_handler()
regardless of your programming pattern.
But if you are doing it in OOP you should make use of magic methods(what?) like __call
and __get
-obviously the $haha
needs to be the object in your example.
Hint: Using
Exception
in magic methods is really good idea. but you can't handle this directly with exception because Internal PHP functions mainly use Error reporting, only modern Object oriented extensions use exceptions.
Upvotes: 1
Reputation: 1358
I would try something like:
<?php
for ($i = 1; $i <=20; $i++) {
echo $i . '<br />';
if ($i == 10) {
if ($haha) $haha->hoho("hehe");
}
}
?>
This should check if $haha
exists before it tries to do $haha->hoho("hehe");
Upvotes: 0