上述课程有什么问题?基本上我想要从奥迪,福特,欧宝课程到全部或两个3级(公共方法)。 例如,在其中一个奥迪对象方法中可以访问欧宝的公共方法,如:
[奥迪]函数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
答案 0 :(得分:1)
您可以在类Factory中使用getter:
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