I have already read about encapsulation and from my understanding, the benefit is to prevent changing the value of property? (please warning me if I misunderstand)
However, it has a method setter that change the value of property private $bar
Am I misunderstand? because it's not prevent changing value of property anymore.
<?php
class Foo
{
private $bar = 3;
public function getbar()
{
return $this->bar;
}
public function setBar($bar)
{
$this->bar = $bar;
}
}
$foo = new Foo();
echo $foo->getbar(); //Print '3'
$foo->setBar("Hello");
echo $foo->getbar(); //Print 'Hello'
?>
so now I am confuse why just they don't use public property normally.
class Foo2
{
public $bar = 3;
}
$foo2 = new Foo2();
echo $foo2->bar; // Print '3'
$foo2->bar = 'Hello';
echo $foo2->bar; //Print 'Hello';