Jump to content

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


Go to solution Solved by 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!

Edited by Hubble
  • Solution

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 by Hubble
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.