0
class config {
    public $pageName;

    function __construct($pageName=''){
        $this->pageName = $pageName;        
    }
}


class header extends config {
    function display(){
        echo parent::$this->pageName;
    }

}


$config = new config('Home Page');
$header = new header();
$header->display();

这不显示任何内容,我认为它应该显示“主页”。

知道我怎么能做到这一点吗?

4

4 回答 4

4

The $header object has no relationship to the $config object. Just because their class hierarchy is connected doesn't mean that the object instances share data.

$config1 = new config('Home Page');
$config2 = new config();

Here $config2 couldn't access the value 'Home Page' either, because it's a different object. It's not a matter of class hierarchy.

于 2012-04-04T08:37:15.720 回答
1

你想组合你的对象而不是继承它们的类(又名控制反转,依赖注入):

interface IConfig {
  public function pageName();
}
class Config implements IConfig {
    private $pageName;
    public function pageName() { return $this->pageName; }

    function __construct($pageName=''){
        $this->pageName = $pageName;        
    }
}


class Header {
    private $config;

    function __construct(IConfig $config) {
      $this->config = $config;
    }

    function display(){
        echo $this->config->pageName();
    }

}


$config = new Config('Home Page');
$header = new Header($config);
$header->display();
于 2012-04-04T08:39:48.113 回答
1
$header = new header('Home Page');
$header->display();
于 2012-04-04T08:40:01.330 回答
0
$header = new header('Home Page');
$header->display();
于 2012-04-04T08:43:03.243 回答