简体   繁体   中英

PHP multiple child classes, accessing child class to class

I'm not entirely sure if this a understanding problem or syntax. I am trying to access child classes from other child classes under the same parent.

    class TopLevel {
    foreach (glob("assets/php/*.php") as $filename) // will get all .php files within plugin directory
      {
        include $filename;
        $temp = explode('/',$filename);
        $class_name = str_replace('.php','',$temp[count($temp)-1]); // get the class name 
        $this->$class_name = new $class_name;   // initiating all plugins
      }
    }

    class A extends TopLevel {
        $var = 'something';
        public function output() {
            return $this->var;
        }
    }

    class B extends TopLevel {
        // This is where I need help, CAN the child class A be accessed sideways from class B? Obviously they need to be loaded in correct order of dependency.
        $this->A->output();
    }

I don't see why this shouldn't work. Not very good structure but its a single object application.

The answer is: No, the child class A cannot be accessed sideways. There is no direct inheritance between A and B.

The answer might be to typecast $this->A into an object of type B using a function like the one in the answer to this question:

How to Cast Objects in PHP

Make object of class A inside B and then call method of A as there is No parent child relationship between A , B.

   $objOfA = new A();
   $objOfA->output();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM