1

Looking at PHP documentation, they say

Any valid code may appear inside a function, even other functions and class definitions.

Is there a use case for a class definition inside a function? I've seen function definitions inside a function, especially anonymous functions, but what about classes?

MC Emperor
  • 22,334
  • 15
  • 80
  • 130
bg17aw
  • 2,818
  • 1
  • 21
  • 27
  • 1
    Even if there is a usecase for that, it is still a very very bad design. Hands off! – B001ᛦ Aug 27 '15 at 09:55
  • 2
    `PHP 7` will support anonymous classes see here http://stackoverflow.com/questions/9726396/anonymous-class-construction – Alex Andrei Aug 27 '15 at 09:56
  • @Alex Andrei, thanks, that's very interesting, would probably be worth posting that info in an answer as well. – bg17aw Aug 27 '15 at 10:08
  • 1
    @bg17aw That's actually not what OP was asking for. An anoymous class exists just inside of the created context and can't be referenced any where else, whereas a proper class definition is accessible from everywhere. Usecases for OP's question might be class loaders. – Markus Malkusch Aug 27 '15 at 10:12
  • @bub, can you expand that in an answer? If it is indeed bad practice, I would sure like to know that, and especially WHY. – bg17aw Aug 27 '15 at 10:49

2 Answers2

1

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.

deceze
  • 510,633
  • 85
  • 743
  • 889
1

Have a look into an arbitrary class loader (e.g. Composer's ClassLoader::includeFile()) I would say they all will require/include the requested class within a method which effectively is defining a class within that method.

That being said for class methods, you can now if you want create a class loader which is just a function. Also note that the first class loaders in PHP could only be made by implementing the function __autoload().

Markus Malkusch
  • 7,738
  • 2
  • 38
  • 67