Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access parent properties in child using $this

Tags:

oop

php

I am trying to create a simple MVC my personal use and I could really use an answer to this simple question

class theParent extends grandParent{

    protected $hello = "Hello World";

    public function __construct() {
        parent::__construct();
    }

    public function route_to($where) {
        call_user_func(array("Child", $where), $this);
    }
}

class Child extends theParent {

    public function  __construct() {
        parent::__construct();
    }

    public function index($var) {
        echo $this->hello;
    }

}

$x = new theParent();
$x->route_to('index');

Now Child::index() this throws a fatal error: Using $this when not in object context but if I were to use echo $var->hello, it works just fine.

I know I can use $var to access all properties in the parent, but I would rather use $this.

like image 308
Rohit Chopra Avatar asked Jun 15 '11 20:06

Rohit Chopra


2 Answers

By writing call_user_func(array("Child", $where), $this) you are calling the method statically. But as your method isn't static you need some kind of object instance:

call_user_func(array(new Child, $where), $this);

Documentation on callback functions.

like image 108
NikiC Avatar answered Sep 30 '22 10:09

NikiC


You don't have an instance of Child to call a non-static method upon when you're doing $x->route_to('index'); The way you're calling the method, without having made an instance first, is implied static.

There are two ways to correct it. Either make the Child class's methods static:

class Child extends theParent {

    public function  __construct() {
        parent::__construct();
    }

    static public function index($var) {
        echo self::$hello;
    }

}

...or make an instance of the child class for the parent to use:

   class theParent extends grandParent{

        protected $hello = "Hello World";
        private $child = false

        public function __construct() {
            parent::__construct();
        }

        public function route_to($where) {
            if ($this->child == false)
              $this->child = new Child();
            call_user_func(array($this->child, $where), $this);
        }
    }

Of course, both of these samples are rather generic and useless, but you see the concept at hand.

like image 23
Chris Baker Avatar answered Sep 30 '22 12:09

Chris Baker