I would like just to like to ask for a little elucidation about this three code snippets I found and how PHP behaves with them:
1) a php class (tmp.class.php) with a static method call:
<?php
class Dummy {
public function sayHello()
{
echo "HELLO FROM DUMMY";
}
public static function requireScript() {
require __DIR__ . "/tmp2.php";
}
}
Dummy::requireScript();
2) another file (tmp1.php), instantiating the previous defined class:
<?php
require_once __DIR__. "/tmp.class.php";
$obj = new Dummy;
?>
3) another file (tmp2.php), using the previous instance of the class:
<?php
require_once __DIR__ ."/tmp1.php";
$obj->sayHello();
?>
Now I know that as the requireScript() method has a require call in it, in fact the tmp2.php is included twice, am I right? But when I make the script run (open the tmp2.php file in the browser) I get a Notice: Undefined variable: obj and then of course a Fatal error because of the sayHello();
Shouldn't the $obj be available to the second required tmp2.php script? What is wrong with this code?
Thanks for attention!
In fact noone should build PHP application in that way. You shouldn't put require / include in many files. In simple application you should run require / include at the beginning of file to have everything you need. In more complex applications you should simple use Object Oriented Programming and use autoloader to load classes definitions when they are needed