In the development of a website, I encountered this problem. I want to pass an object into a class, and afterwards I’d like to use it’s methods. Here’s what I’m trying to do:
[updated code below]
First I create a new theme and header. Then I’d like to use the newly created $theme in my Header class. So I need to pass it. I want to use the same instance of $theme in multiple classes, so I can’t create a new one. Also I’d like to avoid using a Singleton.
With my current code I’m getting this error:
Fatal error: Call to a member function getHeader() on a non-object in...
My questions:
- Is this approach going to work or is it completely wrong?
- How can I pass an object to another object and then still be able to use it’s methods?
- Might it be better to use a singleton instead and use Theme::getInstance(); to use it in the other class?
[edit]
More detailled code:
$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 builder class:
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;
}
}
Your approach works fine in the following code:
Perhaps there’s something else that’s stopping it from working?
EDIT
A quick spot, you mistyped construct:
EDIT2 I found your error:
When
new HeaderBuilder()gets called:$this->build();gets executed in your AbstractBuilder:Which points to
In your HeaderBuilder.. BUT! That $this->build(); is being called before the $header->setTheme() is being called, so the $theme variable in HeaderBuilder is empty.
Commenting out that $this->view = … line makes the code work again.