OOP реальный мир сценарий:
Представьте, что вы есть класс Vehicles
и у них есть (protected
) wheels
. У вас разные Vehicles
с wheels
, но до addWheel
до Bike
, отличается от addWheel
до Aircraft
.
Код преимущество:
Использование геттер и сеттер, вы можете использовать typehinting
.
Сравните эти отрывки:
class Car {
public $wheels;
}
$bmw = new Car;
$bmw->wheels = 'piece of paper';
Приведенный выше код позволяет вам добавить что-нибудь в качестве wheel
, но вы можете использовать кусок бумаги, как колесо?
Теперь с геттер и сеттер:
class Car {
protected wheels;
public function __construct() {
$this->wheels = new ArrayIterator;
}
public function addWheel(Wheel $wheel) {
$this->wheels->add($wheel);
return $this;
}
public function removeWheel(Wheel $wheel) {
$this->wheels->remove($wheel);
return $this;
}
}
class Wheel {
}
$bmw = new Car;
$bmw->addWheel('piece of paper'); // <-- throws an error!
// paper cannot be used as a wheel
$bmw->addWheel(new Wheel); // <-- good :-)
Больше кода, чтобы быть более простым.Представьте, у вас есть RearWheels
и FrontWheels
: [? Зачем использовать добытчиками и сеттеров]
class Wheel {
}
class FrontWheel extends Wheel {
}
class RearWheel extends Wheel {
}
class Car {
protected wheels;
public function __construct() {
$this->wheels = new ArrayIterator;
}
public function addWheel(Wheel $wheel) {
// check for already existing Wheels here.
// Pseudo Code:
if (wheels typeof RearWheel > 2) {
throw new Exception('cannot add more than 2 RearWheels to the Car');
}
return $this;
}
public function removeWheel(Wheel $wheel) {
$this->wheels->remove($wheel);
return $this;
}
}
возможный дубликат (https://stackoverflow.com/questions/1568091/why-use-getters-and-setters) – Boann
Вот отличный ответ: [? Зачем использовать добытчик и сеттер] [1] [1]: http://stackoverflow.com/a/1568230/3916476 – tenhsor