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();
This doesn't display anything, I thought it should have displayed 'Home Page'.
Any idea how i can achieve this?
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.
header instance to have access to data, the data needs to be injected into it somehow. The expectation seems to be to instantiate two different objects which can automatically share data though, which is not an expectation I can offer a reasonable solution for - deceze 2012-04-04 08:53
header object with the correct constructor call will allow this. Another possibility is to use two objects together with dependency injection - knittl 2012-04-04 08:58
You want to compose your objects instead of inherit their classes (a.k.a. Inversion of Control, Dependency Injection):
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();
$header = new header('Home Page');
$header->display();
$header = new header('Home Page');
$header->display();
header class just to call the parent's constructor. Just leave all that out, the constructor is inherited like everything else - deceze 2012-04-04 08:50
echo $this->pageName;Sachin 2012-04-04 08:35