2

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.

  • 1
    There is no relation between A and B as far as I can see? – PeeHaa Feb 17 '15 at 23:40
  • Also you might want to look into [proper autoloading](http://php.net/manual/en/function.spl-autoload.php) instead of whatever it is your doing now. – PeeHaa Feb 17 '15 at 23:41
  • Your code is incomplete, but what you're trying to do should work if the foreach is in the constructor of the TopLevel class. – Dragony Feb 18 '15 at 00:02
  • I used this autoloding because it initiates the sub class as an object inside the main. Like I said, this structure is not correct. The relation for example would be template data in class A and the flow/logic is in Class B. – Eric Samuel Feb 18 '15 at 00:06
  • I was not asking about that kind of relation. How would instance A be aware of instance B. Or the other way around? – PeeHaa Feb 18 '15 at 00:23
  • Opps your right, They don't directly, only via parent. I did type $self there, as stated could simply be syntax error; but its not normal structure of code. It should be parent::A->output(); TopLevel has each child stored, I have tried with parent but it results in same non-object. – Eric Samuel Feb 18 '15 at 00:40
  • @EricSamuel : At least care to check ansewrs or we just wasted time reading and answering your question? – Pratik Joshi Feb 20 '15 at 05:07
  • Ok, sorry. Tried to up click but I guess its the check. Thanks for the help. – Eric Samuel Feb 21 '15 at 14:40

2 Answers2

0

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

Community
  • 1
  • 1
delatbabel
  • 3,601
  • 24
  • 29
0

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();
Pratik Joshi
  • 11,485
  • 7
  • 41
  • 73