Okay, I've often had some unsolved errors when it comes to accessing several other classes in one class.
Depending on which class gets required first, it will not make it accessible in the __construct function in the other files.
Undefined property: Container::$Core in /usr/share/nginx/html/app/classes/class.users.php on line 9
class.container.php
public function __construct() {
if(isset(self::$class)) {
foreach(self::$class as $key => $value) {
if(!isset($this->{$key})) {
$this->{$key} = $value;
}
}
}
}
public function setClassHandlers($class = []) {
if(!isset(self::$class)) {
foreach($class as $name => $file) {
$file = DIR . "app/classes/" . $file;
if(!isset(self::$library[$name])) {
// Get interface file
$interface = DIR . "app/classes/interfaces/interface.".strtolower($name).".php";
// Check if interface file exists
if(!file_exists($interface)) {
// Throw exception
$this->throwException("Unable to load interface file: {$interface}");
}
// Require interface
require_once $interface;
//Check if interface is set
if(!interface_exists("i".ucfirst($name))) {
// Throw exception
$this->throwException("Unable to find interface: {$interface}");
}
// Check if class file exists
if(!file_exists($file)) {
// Throw exception
$this->throwException("Unable to load class file: {$file}");
}
// Require class
require_once $file;
// Check if class file exists
if(class_exists($name)) {
// Set Library
self::$library[$name] = $file;
// Set interface
self::$interface[$name] = $interface;
// Set class // class.container.php
self::$class[$name] = new $name(new self);
$this->{$name} = self::$class[$name];
} else {
// Thror error
$this->throwException("Unable to load class: {$name}", self::$library[$name]);
}
}
}
}
}
Inserting arguments into the function on index.php:
require_once DIR . 'app/management/dependency.php';
$container = new Container();
$container->setClassHandlers([
// Name // Path
'Database' => 'class.database.php',
'Config' => 'class.config.php',
'Users' => 'class.users.php',
'Core' => 'class.core.php',
//'Admin' => 'class.admin.php',
//'Forum' => 'class.forum.php',
//'Template' => 'class.template.php'
]);
class.users.php
public function __construct(Container $class) {
$this->db = $class->Database;
$this->core = $class->Core;
$this->ip = $this->core->userIP();
$this->container = $class;
}
For example both Users and Core are used within the same file of eachother, but as mentioned above, if Core gets required first, Users is not an available dependency inside that class.
I'm not really quite sure how to fix this, so every help is appreciated.
$file = DIR . "app/classes/" . $file;It should be__DIR__dirname(__FILE__) . DIRECTORY_SEPARATOR, but whats the difference between that and__DIR__?__DIR__is magic constant, similar to__FILE__. Always points to the dir where the current file is. For clarity sake, wouldn't advise on usingDIR. UseWEBROOTor something more explicit, IMO. native__DIR__doesn't include trailing slash though.