Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I include a class inside an method?

Tags:

php

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();
}
like image 657
openfrog Avatar asked Jan 11 '10 19:01

openfrog


People also ask

Can we write inner class in main method?

main method in inner classes Inside inner class we can't declare static members. So that it is not possible to declare main() method inside non static inner class.

Can you create an object inside a method?

In Java, we can create Objects in various ways: Using a new keyword. Using the newInstance () method of the Class class. Using the newInstance() method of the Constructor class.

Can we create a class inside a method in C#?

A nested class can be declared as a private, public, protected, internal, protected internal, or private protected. Outer class is not allowed to access inner class members directly as shown in above example. You are allowed to create objects of inner class in outer class.


1 Answers

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.

like image 189
zombat Avatar answered Nov 05 '22 10:11

zombat