1

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?

2 Answers 2

1

The Simple answer: Fix your code.

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.

Sign up to request clarification or add additional context in comments.

2 Comments

you can write example for me about code above ? document about Exception unintelligible for me :(
Check the example on the Exception on the official PHP Documentation that I have linked, I wouldn't be able to write simpler then that anyways.
0

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");

2 Comments

this is first solution for me, but in my function use a lot of $haha so i can not use if($haha) because look at complicated
"Looks complicated" is not a good reason not to do something pretty standard and simple.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.