A class definition inside a function won't be parsed unless and until that function is run. The same goes for any sort of definition inside an if
statement. There's a use for definitions inside if
statements:
if (!function_exists('foo')) {
function foo ..
}
This is useful for backward compatibility shims and such. And extending this to also work inside functions makes perfect sense, why wouldn't you want to encapsulate your shim code into a function?
Beyond conditionally declaring classes and functions, there's no real use for this. Classes and functions declared this way are globally accessible like any other class or function, only their declaration is delayed until the function is called. Also note that you'll trigger an error if you call such a function twice (class Foo already defined
), unless you take precautions like class_exists
.