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.
You want to compose your objects instead of inherit their classes (aka 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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.