Jump to content

Require all files and assign instances of their classes to main class' properties


Hubble

Recommended Posts

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!

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.