Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php require class call from inside method

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?

like image 605
Jeremy Gwa Avatar asked May 02 '10 23:05

Jeremy Gwa


1 Answers

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.

like image 70
timdev Avatar answered Nov 15 '22 15:11

timdev