tags:

views:

59

answers:

3

Just for the case the autoload thing won't work, I wonder if it's fine with PHP to include a class inside a method?

Example:

public method doSomething() {
   include ('MyClass.php');
   $foo = MyClass::doAnotherThing();
}
+2  A: 

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

Tor Valamo
+1  A: 

Well in that case you probably want to do a require or require_once and probably test if the class_exists, but yes you can do that.

prodigitalson
+3  A: 

Yes, you can definitely do that. In fact, that's exactly what the auto-loading does anyway, since __autoload() is itself a function, and you generally use it to look around for your class file to load.

If you manually include your class files like that however, you'll definitely want to use require_once() rather than include() or require(), otherwise you'll get a duplicate declaration of the class.

zombat
+1 for autoload and *_once()
Kevin Peno