You can declare a class inside a function. This is called a conditional declaration, i.e. Only when the function is called will the class be declared. It doesn't really matter whether you include class declaration file or if you select the code inside the function.
This does not mean, however, that classes have a common view or data. Only an ad is conditionally nested, it still has the same functionality and scope as previously described .
Your confusion about the callback can be explained by the same thing. When class_1::function_1 is executed for the first time, function callback_function defined. This is a regular global function that can be called from anywhere. This has nothing to do with the class. You will also notice that the second time you cannot execute class_1::function_1 , PHP will complain that the callback_function already exists when you try to declare it again.
Regarding the comment in the source code //How do I declare this variable so that it is available where I need it? : you do not do this. This variable is a local variable inside the function. This is only in the area inside the function. You can return its value from the function, like any other return value if you want. (You can make it global , but not for the love of God!) If you need this value somewhere else, do not declare it as a variable inside the function, because only the function can access it.
source share