[英]Using passed objects in PHP5
在开发网站时,我遇到了这个问题。 我想将一个对象传递给一个类,然后再使用它的方法。 这是我想做的事情:
[下面的更新代码]
首先,我创建一个新的主题和标题。 然后,我想在Header类中使用新创建的$ theme。 所以我需要通过。 我想在多个类中使用$ theme的同一实例,因此无法创建新实例。 我也想避免使用Singleton。
用我当前的代码,我得到这个错误:
Fatal error: Call to a member function getHeader() on a non-object in...
我的问题:
[编辑]更详细的代码:
$theme = new Theme($db);
$builder = new Builder($login, $db, $theme);
$builder->build();
Builder.php:
class Builder {
private $login;
private $db;
private $theme;
public function __construct($login, $db, $theme){
$this->login = $login;
$this->db = $db;
$this->theme = $theme;
}
public function build(){
$this->buildHeader();
$this->buildContent();
$this->buildFooter();
}
public function buildHeader(){
$header = new HeaderBuilder($this->login, $this->db);
$header->setTheme($this->theme);
$header->render();
}
public function buildContent(){}
public function buildFooter(){}
}
抽象生成器类:
abstract class AbstractBuilder {
private $variable = array();
private $login;
private $db;
private $view;
abstract function build();
public function __construct($login, $db){
$this->login = $login;
$this->db = $db;
$this->build();
}
public function render(){
extract($this->variable);
include($this->view);
}
}
HeaderBuilder:
class HeaderBuilder extends AbstractBuilder {
private $theme;
public function build(){
$this->view = $this->theme->getHeader();
}
public function setTheme($theme){
$this->theme = $theme;
}
}
您的方法在以下代码中工作正常:
$theme = new Theme();
$header = new Header();
$header->setTheme($theme);
$header->build();
class Header {
private $theme;
public function setTheme($theme){
$this->theme = $theme;
}
public function build(){
$this->view = $this->theme->getHeader();
}
}
class Theme {
public function getHeader() {
echo 'yes';
}
}
也许还有其他原因阻止了它的正常运作?
编辑
快速点,您输入了错误的构造:
public function __constuct($login, $db, $theme){
$this->login = $login;
$this->db = $db;
$this->theme = $theme;
}
EDIT2我发现了您的错误:
当new HeaderBuilder()
被调用时:
$header = new HeaderBuilder($this->login, $this->db);
$this->build();
在您的AbstractBuilder中执行:
public function __construct($login, $db){
$this->login = $login;
$this->db = $db;
$this->build();
}
指向哪
public function build(){
$this->view = $this->theme->getHeader();
}
在您的HeaderBuilder中。 那$ this-> build(); 在$ header-> setTheme()被调用之前被调用,因此HeaderBuilder中的$ theme变量为空。 注释掉$ this-> view = ...行使代码再次工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.