我正在创建一个相互扩展的小型多类系统。假设类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->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!
)
有人能帮我吗?
这是因为您已经将所有类变量声明为private
。这使得只有声明它们的类才能访问它们。即使是子类(派生类)也看不到它们。
如果需要子类来访问父类的变量,则应将它们声明为protected
。
http://php.net/manual/en/language.oop5.visibility.php
您应该使用protected
而不是private
!
尝试
protected $head;
protected $out;