from my understanding, require pastes code into the calling php file.
what if you were requiring from inside a method...it would paste the entire code/class inside the method, blocking the next statement in the method.
eg.
function test() {
require 'pathtosomeclasscode';
somestatement; // any code after the require is blocked.
}
how do i get around this, to be able to require code where-ever, without it being pasted in that exact spot?
Somewhat surprisingly, this appears to work just fine. The included code will execute inside the scope of Baz::bork() -- but the the code simply defines a class, and classes are global. So you end up with a defined class.
File: Foo.php:
<?PHP
class Foo{
function bar(){
echo "Hello from Foo::bar()!\n";
}
}
File: Baz.php:
<?PHP
class Baz{
function bork(){
require_once "Foo.php";
$f = new Foo();
$f->bar();
}
}
echo "testing internal definition:\n";
$b = new Baz();
$b->bork();
echo "\ntesting in global scope:\n";
$f = new Foo();
$f->bar();
echo "\nall done\n";
Output:
$ php Baz.php
testing internal definition:
Hello from Foo::bar()!
testing in global scope:
Hello from Foo::bar()!
all done
Now, I can't think of many places where you'd want to do things this way. People typically require_once() any possible dependencies at the top of their class file, outside of the class definition.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With