一位游客想要参观全部 5 个景点。我需要创建一个类来计算访问者访问所有景点一次需要支付的费用。我真的不知道如何在 PHP 中最好地做到这一点。我如何确保它以整齐的轮廓写得工整?
<?php
//attraction class
class Attraction
{
private $name;
private $capacity;
private $ticketPrice;
public function __construct($name, $capacity, $ticketPrice)
{
$this->name = $name;
$this->capacity = $capacity;
$this->ticketPrice = $ticketPrice;
}
public function __get($property)
{
if (property_exists($this, $property)) {
return $this->$property;
}
}
public function __set($property, $value) {
if (property_exists($this, $property)) {
$this->$property = $value;
}
}
public function display() {
$result .="Naam" .$this->name . "<br>";
$result .="Capaciteit" .$this->capacity . "<br>";
$result .="TicketPrijs" .$this->ticketPrice ."Euro<br>";
return $result;
}
}
//the rollercoaster class and parrent
class RollerCoaster extends Attraction
{
private $height;
private $speed;
public function __construct($name, $capacity, $ticketPrice, $height, $speed)
{
$this->height = $height;
$this->speed = $speed;
parent::__construct($name, $capacity, $ticketPrice);
}
public function __get($property)
{
if (property_exists($this, $property)) {
return $this->$property;
}
}
public function __set($property, $value) {
if (property_exists($this, $property)) {
$this->$property = $value;
}
}
}
//this is the code from the Rollercoaster class
我尝试自己创建一个概述类,但效果不太好。
创建接口:
<?php
declare(strict_types=1);
interface Attraction
{
public function calculatePrice(): int
}
创建景点:
<?php
declare(strict_types=1);
class RollerCoaster implements Attraction
{
public function calculatePrice(): int
{
// calculate price by RollerCoaster conditions
}
}
<?php
declare(strict_types=1);
class WatterSlide implements Attraction
{
public function calculatePrice(): int
{
// calculate price by WatterSlide condtions
}
}
创建景点集合:
<?php
declare(strict_types=1);
class AttractionCollection
{
private array $attractions;
public function add(Attraction $attraction) {
$this->attractions[] = $attraction;
}
}
创建计算总价的服务:
<?php
declare(strict_types=1);
class PriceCalculatorService
{
public function totalAttractionsPrice(AttractionCollection $attractions): int
{
$total = 0;
foreach($attractions->getAttraction() as $attraction){
$total += $attraction->calculatePrice();
}
return $total;
}
}
打印价格:
<?php
declare(strict_types=1);
$attractionCollection = new AttractionCollection();
$rollerCoaster = new RollerCoaster();
$waterSlide = new WaterSlide();
$attractionCollection->add($rollerCoaster);
$attractionCollection->add($waterSlide);
$priceCalculator = new PriceCalculatorService();
$totalPrice = $priceCalculator->totalAttractionsPrice($attractionCollection);
echo $totalPrice;