class Street { protected $speedLimit; protected $cars; public function __construct($speedLimit = 200) { $this->cars = array(); // 对变量进行初始化 $this->speedLimit = $speedLimit; } protected function isStreetLegal(Car $car) { if ($car->getMaximumSpeed() < $this->speedLimit) { return true; } else { return false; } } public function addCar(Car $car) { if ($this->isStreetLegal($car)) { echo 'The Car was allowed on the road.'; $this->cars[] = $car; } else { echo 'The Car is too fast and was not allowed on the road'; } } } $street = new Street(); $street->addCar(new FastCar());
public function __construct($speedLimit = 200) { $this->cars = array(); $this->speedLimit = $speedLimit; } public function isStreetLegal($car) { if ($car instanceof ISpeedInfo) { if ($car->getMaximumSpeed() < $this->speedLimit) { return true; } else { return false; } } else { // 扩展类必须实现ISpeedInfo才能使street合法 return false; } } public function addCar($car) { if ($this->isStreetLegal($car)) { echo 'The Car is was allowed on the road'; $this->cars[] = $car; } else { echo 'The Car is too fast and was not allowed on the road'; } } } $street = new Street(); $street->addCar(new Car());