Hubble Posted February 18, 2014 Share Posted February 18, 2014 I want to require_once all of the files in my directory and assign instances of their classes to properties in the main class. Main class (Test.php): <?php error_reporting(E_ALL); class Test { public $egg; public function __construct() { $this->getInstances(); $this->egg->msg("Hello!"); // line 11 } public function getInstances($folder = null) { if($folder != null) { foreach(glob("$folder/*.php") as $file) { require_once $file; $class = basename($file); if(class_exists($class)) { $lclass = strtolower($class); if(property_exists($this, $lclass)) { $this->$lclass = new $class(); } } } } else { foreach(glob("*.php") as $file) { require_once $file; $class = basename($file); if(class_exists($class)) { $lclass = strtolower($class); if(property_exists($this, $lclass)) { $this->$lclass = new $class(); } } } } } } $test = new Test(); ?> Sample class (Egg.php): <?php class Egg { public function msg($msg) { echo $msg . chr(10); } } ?> What it outputs: Fatal error: Call to a member function msg() on a non-object in Test.php on line 11 What I want it to output: Hello! Link to comment https://forums.phpfreaks.com/topic/286290-require-all-files-and-assign-instances-of-their-classes-to-main-class-properties/ Share on other sites More sharing options...
requinix Posted February 18, 2014 Share Posted February 18, 2014 basename() will return the file with the extension as well. Use its second parameter to omit that. Link to comment https://forums.phpfreaks.com/topic/286290-require-all-files-and-assign-instances-of-their-classes-to-main-class-properties/#findComment-1469423 Share on other sites More sharing options...
Hubble Posted February 18, 2014 Author Share Posted February 18, 2014 basename() will return the file with the extension as well. Use its second parameter to omit that. I changed it to basename($file, ".php") and I still get the error. EDIT: It works now, I also had a few other mistakes which I fixed. Link to comment https://forums.phpfreaks.com/topic/286290-require-all-files-and-assign-instances-of-their-classes-to-main-class-properties/#findComment-1469426 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.