PHP堆栈类什么都不返回

时间:2014-11-12 14:11:48

标签: php class stack extends

我正在创建一个相互扩展的小型多类系统。让我们说a级是一个"核心"并作为检查/管理包装工作。 b类是检查$d是什么,并调用类c的方法,用户类(如果存在)或触发错误以对其进行分类。

这是我的代码:

<?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();

?>    

如果我运行$c->output()它没有返回任何内容,但print_r()会返回此信息:

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!
)

有人可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:2)

这是因为您已将所有类变量声明为private。这使得只有声明它们的类才能访问它们。甚至子类(派生类)也看不到它们。

如果您需要子类来访问父类的变量,则应将它们声明为protected

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

答案 1 :(得分:1)

您应该使用protected代替private

尝试

protected $head;
protected $out;