PHP - 构造新类时访问创建者类的属性

时间:2018-01-06 11:35:23

标签: php class oop

我正在尝试创建以下设置:

class Car {
    public $brochure;
    public function getBrochure() {
        $this->brochure = new Brochure();
    }
}

class Jeep extends Car {
    ...
    public $terrain = 'dirt';
}

class SportsCar extends Car {
    ...
    public $terrain = 'racing tracks';
}

然后,我想要小册子课:

class Brochure {
    public $advertisement_text;
    public function __construct() {
        ...
        if($terrain) {
            $str = $str ."This car is best driven on $terrain!\r\n";
        }
        ...
        $this->advertisement_text = $str;
    }
}

显然,$terrain变量不存在。我总是可以把它作为一个参数传递给我,但我想知道是否可以访问创建者类的公共属性而不传递它们?

2 个答案:

答案 0 :(得分:0)

最好在构造函数中传入变量,我已经改变了一些东西(我在代码中添加了注释适用)...

class Brochure {
    public $advertisement_text;
    // Create brochure with the terrain
    public function __construct( $terrain ) {
        $str = "This car is best driven on $terrain!\r\n";
        $this->advertisement_text = $str;
    }
}

class Car {
    public $brochure;
    public $terrain = '';
    public function getBrochure(  ) {
        // Only set value if not already set
        if ( $this->brochure == null ){
            // Pass the terrain from the current object creating the brochure
            $this->brochure = new Brochure($this->terrain);
        }
        // Return the brochure created
        return $this->brochure;
    }
}

class Jeep extends Car {
    public $terrain = 'dirt';
}

class SportsCar extends Car {
    public $terrain = 'racing tracks';
}

$car = new SportsCar();
$brochure = $car->getBrochure();
echo $brochure->advertisement_text;

这输出......

This car is best driven on racing tracks!

如果您需要为您的宣传册提供大量数据,这可能变得非常复杂,有时使用不同的方法可能会提供更多的未来验证,但这应该是一个开始。

答案 1 :(得分:0)

When you create object of Brochure class pass argument of SportsCar class object like this:

class Brochure {
    public $advertisement_text;
    public function __construct($SportsCar) {
        ...
        if($terrain) {

            $str = $str ."This car is best driven on $SportsCar->$terrain!\r\n";
        }
        ...
    $this->advertisement_text = $str;
}


    $SportsCar=new $SportsCar();
    $Brochure =new $Brochure($SportsCar);