0
class MyClass {

    public function __construct(){
    }

    private function makeError(){
        return sp('ABC'); // sp is undefined function
    }

    private function printMe(){
        echo "PRINT ME";
    }

    public function run(){

        try {
            $t = $this->makeError();

        }catch(Exception $e){
        }

        $this->printMe();       
    }
}

$t = new MyClass();
$t->run();

If run above code, an error occur because sp() is not defined function.

But I'd like to ignore the error and run printMe method.

How should I do?

Thanks!

1
  • What type of error does this throw? Commented Dec 13, 2011 at 17:03

3 Answers 3

1

You could use function_exist()

class MyClass {

    public function __construct(){
    }

    private function makeError(){
        if(!function_exist('sp')){
             throw new Exception();
        }else{
             return sp('ABC'); // sp is undefined function
        }
    }

    private function printMe(){
        echo "PRINT ME";
    }

    public function run(){

        try {
            $t = $this->makeError();

        }catch(Exception $e){
        }

        $this->printMe();       
    }
}

you can't catch the fact that it does'n exist because it's a fatal error

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

Comments

0

That's not possible. It's a fatal error, not an exception.
Therefore it cannot be catched.

In this very instance you can eschew causing the error however with:

if (function_exists("sp")) {
     return sp('ABC'); // sp is undefined function
}

Likewise you could wrap your $this->makeError(); call with that test. But that would mean handling another methods interna. And anyway, that would just avoid that super specific edge case.

Comments

0

As answered already, this is a fatal error: you can't use your own error handler, the best would be to test if the function is available with function_exists.

You may also be able to use somme buffering to do some tricks as explained in this SO anwser: set_error_handler Isn't Working How I Want It To Work

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.