【问题标题】:PHP stacking classes returns nothingPHP 堆叠类不返回任何内容
【发布时间】:2014-11-12 14:11:48
【问题描述】:

我正在创建一个相互扩展的小型多类系统。可以说 a 类是一个“核心”,并作为检查/管理包装器工作。 b 类是检查$d 是什么,如果存在则调用用户类c 类的方法,否则触发错误返回给a 类。

这是我的代码:

<?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-&gt;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!
)

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

【问题讨论】:

    标签: php class stack extends


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      您应该使用protected 而不是private

      试试

      protected $head;
      protected $out;
      

      【讨论】:

        猜你喜欢
        • 2020-02-22
        • 1970-01-01
        • 1970-01-01
        • 2013-10-22
        • 1970-01-01
        • 2021-07-07
        • 2014-02-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多