Hi,
I was wondering whether it is possible to use a parent class' properties without calling its constructor. In the following example:
<?php
class Shop {
public $location;
public function __construct($location = ''){
if(!empty($location)){
$this->location = $location;
} else {
$this->location = 'a place far far away';
}
$this->location .= '. ';
echo 'Shop constructor has been called. ---- ';
}
public function check_stock($item){
echo 'There are still quite a few '. $item.'s remaining.';
}
}
class Item extends Shop {
//public function __construct(){}
public function find($item){
echo $item . ' can be found at '.$this->location;
$this->check_stock('Bed');
}
}
$shop = new Shop('Carreyville');
$item = new Item;
$item->find('Bed');
// output: Shop constructor has been called. ---- Shop constructor has been called. ---- Bed can be found at a place far far away. There are still quite a few Beds remaining.
?>
In this script, it can be seen that the constructor has been called twice, since the child is called the parent construct again after the parent had already been instantiated. However, if the child doesn't call the parent constructor, the parent's properties cannot be accessed.
<?php
class Item extends Shop {
public function __construct(){}
public function find($item){
echo $item . ' can be found at '.$this->location;
$this->check_stock('Bed');
}
}
// output: Shop constructor has been called. ---- Bed can be found at There are still quite a few Beds remaining.
?>
Is there anyway to access the parent properties without having to call the parent's constructor again since it has already been instantiated before the child.
Thanks.