Search code examples
phpclassparentparent-child

php calling parent function makes parent unable to load own vars


I have a Handler class that looks like this:

class Handler{
    public $group;

    public function __construct(){
        $this->group = $this->database->mysql_fetch_data("blabla query");
        //if i print_r($this->group) here it gives proper result

        new ChildClass();
    }

    public function userGroup(){
        print_r($this->group); //this is empty
                    return $this->group;
    }
}

class ChildClass extends Handler{

    public function __construct(){
        $this->userGroup();
        //i tried this too
        parent::userGroup();
        //userGroup from parent always returns empty
    }

}

Workflow:

  • Handler is called from my index.php and the __construct is called

  • Handler needs to create $group

  • Handler creates child class

  • Child class calls Handler function

  • When I try to return $group in the function It tries to get $this->group from Child instead of Handler

Whenever I try to ask the parent something I can only access the parent function then inside the function the parent class can't find any of it's own variables

EDIT:

I figured using 'extends' would be useful in calling parent functions but it seems just passing $this on to the child will be easier.


Solution

  • You never called the parent constructor, so the group object is never initialized. You will want to do something like this.

    class Handler{
        public $group;
    
        public function __construct(){
            $this->group = $this->database->mysql_fetch_data("blabla query");
            //if i print_r($this->group) here it gives proper result
    
            new ChildClass();
        }
    
        public function userGroup(){
            print_r($this->group); //this is empty
                        return $this->group;
        }
    }
    
    class ChildClass extends Handler{
    
        public function __construct(){
            parent::__construct();
            $this->userGroup();
        }
    
    }
    

    If you had not overwritten the __construct method in your extended class, then the parent __construct would have automatically been called, but since you overwrote it in the extended class, you must tell it to call the parent's __construct in your extended class' __construct.