phpclassobjectinstantiation

In Php what happens when an object fails to be instantiated?


$someClass sc=new SomeClass();

What I want to know is what will be in the variable sc if the constructor fails for some reason (like maybe not enough memory). I can' t find a straight answer?


Solution

  • A constructor can fail for mainly two reasons:

    1. Out of memory; not unique to objects, this causes a fatal error and your script won't continue.

    2. An exception is thrown; your script will stop unless the exception is caught using a 'try-catch' clause.

    try {
        $sc = new SomeClass(); // exception is thrown inside the constructor
    } catch (Exception $e) {
        echo "Yikes, object didn't get created; error = {$e->getMessage()}\n";
    }