在开发网站时,我遇到了这个问题。我想将一个对象传递给一个类,然后我想使用它的方法。这就是我想要做的事情:
[以下更新代码]
首先,我创建一个新的主题和标题。然后我想在我的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;
}
}
答案 0 :(得分:1)
您的方法在以下代码中正常工作:
$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 = ... line会使代码再次运行。