PHP stacking classes returns nothing

88 Views Asked by At

I'm creating a small, multiclass system that extends each other. Lets say class a is a "core" and work as a checking/administration wrapper. class b is to check what $d is and call a method of class c, a user class, if it exists or trigger an error to class a back.

Here's my code:

<?php

class a {

    private $error;
    private $ok;

    public function __construct() {

        $this->error    = array();
        $this->ok       = array();

        // do other stuff here
    }
}

class b extends a {

    private $head;
    private $out;

    public function __construct() {

        parent::__construct();

        global $d;

        $this->head = "";
        $this->out  = "";

        if(method_exists($this,$d)) {
            $this->{$d}();
        } else
            $this->error[] = "method '$d' not found";
    }

    public function output() {
        return ($this->head==""?"":'<h1>'.$this->head.'</h1>').$this->out;
    }
}

class c extends b {

    private $me = "inside c";

    public function standard() {

        $this->head = "Heading";
        $this->out  = "it works!";

    }

}

$d      = "standard";
$c      = new c();

echo "<pre>".print_r($c,true)."</pre>";
echo $c->output();

?>    

if i ran $c->output() it returns nothing, but the print_r() returns this:

c Object
(
[me:c:private] => inside c
[head:b:private] => 
[out:b:private] => 
[error:a:private] => Array
    (
    )

[ok:a:private] => Array
    (
    )

[head] => Heading
[out] => it works!
)

Could anyone please help me with this?

2

There are 2 best solutions below

0
On BEST ANSWER

It's because you've declared all your class variables as private. This makes it so that only the class where they were declared can access them. Not even subclasses (derived classes) can see them.

If you need subclasses to access the variables of a parent class, you should declare them as protected.

http://php.net/manual/en/language.oop5.visibility.php

0
On

You should use protected instead of private!

Try

protected $head;
protected $out;