Q:

Special conditions for finding classes within if-statements?

Let's jump right in to some contextual code. Please read the following...
(1) This works fine:
new myClass();

class myClass{
    // Stuff
}

(2) Doesn't work (fatal error class not found):
if ($_POST['apikey'] == "foo") {
    new myClass();

    class myClass{
        // Stuff
    }
}

(3) Solution to above:
if ($_POST['apikey'] == "foo") {        
    class myClass{
        // Stuff
    }

    new myClass();
}

Can't really find why I needed to do what I did to fix it. I know it's a scripting language, but why would (1) work? Is it some kind of quality of life feature in php that doesn't work once I start nesting it in if-statements or similar?

A:

PHP compiles and parses the script before it runs.  So it knows about definitions before it starts execution of the script.
This would be blocked if you have a conditional definition because the compiler can't possibly know what that condition will equate to until the script is executed.
In my opinion, you should never define a class, function, or constant inside a condition.  That is what variables are for.

