Access parent properties of a child using $ this

I am trying to create a simple MVC for my personal use, and I really could use the 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 raises a fatal error: Using $this when not in object contextbut if I used echo $var->hello, it works fine.

I know that I can use $varto access all the properties in the parent, but I would prefer to use $this.

+5
source share
3 answers

You do not have an instance Childto call a non-static method when you make $x->route_to('index');The way you invoke a method without making the first instance is assumed to be static.

. Child static:

class Child extends theParent {

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

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

}

... :

   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);
        }
    }

, , .

+4

call_user_func(array("Child", $where), $this) . , - :

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

.

+6

$this / . (), /.

- , / parent, ::, , .

Protected variables exist only once, so you cannot use parentto access them.

Is this information used?

+1
source

All Articles