Is it possible to include a class inside a method?

Just for the case, autoload will not work, I wonder if it is good to include a class inside the method with PHP?

Example:

public method doSomething() { include ('MyClass.php'); $foo = MyClass::doAnotherThing(); } 
+6
php
source share
3 answers

Yes you can do it. In fact, this is exactly what autoload does, anyway, since __autoload() itself a function, and you usually use it to find a loadable class file.

If you manually include your class files like this, you will certainly want to use require_once() rather than include() or require() , otherwise you will get a duplicate class declaration.

+3
source share

Yes, this works great, and the class will be available in a global scope. If the file contains other code than the class, this code will be executed as if it were inside a function.

+3
source share

In this case, you probably want to do require or require_once and probably check if there are class_exists , but yes, you can do it.

+1
source share

All Articles