I have a class:
class Test {
public function someFunction()
{
require('SomeOtherClass.php');
}
}
I can't understand how php requires the class here if another class physically can't be inside a function of a class? how php does this? where php puts the class then?
This is perfectly valid code:
function foo() {
class Foobar {
function speak() {
echo "Hi";
}
}
$obj = new Foobar();
$obj->speak();
}
// $obj = new Foobar(); // Will fail, as Foobar will be defined the global scope when running foo();
foo();
$obj = new Foobar(); // Will be OK, now the class is defined in the global scope
//foo(); // Fatal error: Cannot redeclare class Foobar
The output is:
Hi
For details see documentation.
Use the following in the class:
class Test {
public $other_class;
function __construct() {
$this->other_class = new other_class();
}
public function someFunction() {
$this->other_class;
}
}
To use this. Inlcude your classes like this:
spl_autoload_register(function($class) {
include_once 'classes/'.$class.'.php';
});
Use that function in a file that is included everywhere
This is in the documentation for include
:
When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope. (emphasis added)
require
is identical to include
in virtually all respects, including this one.