开发者

Can I include a class inside an method?

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?

Exam开发者_如何转开发ple:

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


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜