Hubble Posted February 18, 2014 Share Posted February 18, 2014 (edited) 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! Edited February 18, 2014 by Hubble Quote Link to comment 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. Quote Link to comment Share on other sites More sharing options...
Solution Hubble Posted February 18, 2014 Author Solution Share Posted February 18, 2014 (edited) 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. Edited February 18, 2014 by Hubble Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.