Classes require a method

I have a class, the method can return an instance of another, ex:

class a { public function foo() { } public function bar() { return new b(); } } 

Class "b" is in another file, I can do:

 require_once('b.php'); class a { public function foo() { } public function bar() { return new b(); } } 

But I am including a class, and this is not use in the mayor of cases. I really do:

 class a { public function foo() { } public function bar() { require_once('b.php'); return new b(); } } 

In fact, do not use the require function, I use the import function that I need to use, but I do this (and not autoload) for class names (we use packages and do not use namespaces).

This works without error, bullying, notification, etc. Is this wrong?

+4
source share
2 answers

This is normal. Make sure you do not have statements that are not part of the class / function, as they will only be executed / available in the bar() function

+2
source

I think this is more a matter of personal choice. Since PHP is interpreted, unlike C for example, the compiler does not need to know the class definitions before runtime, so you can use include directives anywhere in your code.

Both will have an advantage and a disadvantage: if you always include at the beginning of your script, you can easily figure out what dependencies your class has, but you can load classes that will not be used at runtime. Obviously, the opposite effect will have the opposite effect.

Any is allowed.

+2
source

All Articles