[英]How can extend in proper way some php classes for have access from child class to all public methods from other child class?
以上課程有什么問題? 基本上,我想從Audi,Ford,Opel類訪問所有或兩個3類(公共方法)。 例如,在一個Audi對象對象方法中,可以訪問Opel公共方法,例如:
[在Audi中] function otherPrices(){return $ this-> opel-> getPrice(); }
class Car {
function Car() {}
}
class Model extends Car {
public $audi;
public $ford;
public $opel;
function Model() {
parent::Car();
$this->audi = new Audi();
$this->ford = new Ford();
$this->opel = new Opel();
}
}
class Factory {
public $audi;
public $ford;
public $opel;
function Factory(){
$model = new Model();
$this->audi = $model->audi;
$this->ford = $model->ford;
$this->opel = $model->opel;
}
}
class Audi extends Factory {
public $price = 10;
function Audi() {}
function audiVsOpel(){
return "A:" . ($this->price - $this->opel->price);
}
}
class Ford extends Factory {
public $price = 12;
function Ford() {}
function fordVsAudi(){
return "B:" . ($this->price - $this->audi->price);
}
}
class Opel extends Factory {
public $price = 14;
function Opel() {}
function opelVsford(){
return "C:" . ($this->price - $this->ford->price);
}
}
/*
Here a implementation
*/
$factory = new Factory();
echo $factory->audi->audiVsOpel(); // want to echo -4
echo $factory->ford->fordVsAudi(); // want to echo 2
echo $factory->opel->opelVsford(); // want to echo 2
您可以在工廠類中使用吸氣劑:
public function getFactory($factory) {
if (NULL === $this->{$factory}) {
$this->{$factory} = new $factory;
}
return $this->{$factory};
}
然后以這種方式在每個工廠類中獲得不同的工廠對象:
$this->getFactory('opel')->price
您的代碼的工作示例:
class Car {
function Car() {}
}
class Model extends Car {
public $audi;
public $ford;
public $opel;
function Model() {
parent::Car();
$this->audi = new Audi();
$this->ford = new Ford();
$this->opel = new Opel();
}
}
class Factory {
public $audi = NULL;
public $ford = NULL;
public $opel = NULL;
function Factory(){
$model = new Model();
$this->audi = $model->audi;
$this->ford = $model->ford;
$this->opel = $model->opel;
}
public function getFactory($factory) {
if (NULL === $this->{$factory}) {
$this->{$factory} = new $factory;
}
return $this->{$factory};
}
}
class Audi extends Factory {
public $price = 10;
function Audi() {}
function audiVsOpel(){
return "A:" . ($this->price - $this->getFactory('opel')->price);
}
}
class Ford extends Factory {
public $price = 12;
function Ford() {}
function fordVsAudi(){
return "B:" . ($this->price - $this->getFactory('audi')->price);
}
}
class Opel extends Factory {
public $price = 14;
function Opel() {}
function opelVsford(){
return "C:" . ($this->price - $this->getFactory('ford')->price);
}
}
/*
Here a implementation
*/
$factory = new Factory();
var_dump($factory);
echo $factory->audi->audiVsOpel(); // echo -4
echo $factory->ford->fordVsAudi(); // echo 2
echo $factory->opel->opelVsford(); // echo 2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.