You would do this to encapsulate the functionality and protect the using code from change. Take this example:
class Person
{
protected $legs;
public function setLegs($number){
$this->legs = $number;
}
}
Lets presume we now have some code that uses this class...
if ($_POST['legs'])
{
$person = new Person;
$person->setLegs($_POST['legs']);
}
Ofcours you could do this with the following class
class Person
{
public $legs;
}
$person = new Person;
$person->legs = $_POST['legs'];
The problem comes if you need to provide any validation to legs or if you want to make changes later. Let's say you have to make a change to the rules about a person (for example the maximum amount of legs a person can have is ten) - if you havent encapsulated the logic you now need to go all over your app finding its uses...
class Person
{
protected $legs;
public function setLegs($number){
if ( ! is_int($number) || $number > 10){
throw new Exception('incorrect user input');
}
$this->legs = $number;
}
}
Encapsulation is important for the following reasons:
- It allows application logic to be reused
- It makes it possible to make changes easier later