doflamingo
doflamingo

Reputation: 565

PHP OOP - Do getter setter use for prevent changing value of property?

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';

Upvotes: 3

Views: 1136

Answers (2)

Bukharov Sergey
Bukharov Sergey

Reputation: 10185

My opinion is you need avoid public fields, getters and setters as much as possible. Encapsulation is NOT "to prevent changing the value of property". It is all about hiding how concretely class works. All methods of class must define a behavior, but not how exactly this class works.

Let me show a example. The traditional way is:

Dog dog = new Dog();
dog.setBall(new Ball());

But in real world you CAN'T set ball to the dog. You can tell dog to take a ball. And dog will decide he wants to take a ball or not.

OOP way is some like this:

Dog dog = new Dog();
dog.take(new Ball());
Ball ball = dog.give();  

Code above demonstrate how encapsulation works. I recommend read a article why getters and setters are evil. It explains the issue in details

Upvotes: 1

TurtleTread
TurtleTread

Reputation: 1314

Ah, I remember wondering about the same thing when I was first reading about this stuff too. The idea is that you really ENFORCE the restriction of access to property modification. If you have some function that's setting properties of your objects values directly, that's gonna override the properties you have. By specifying specific functions and limit the access to only the class itself or children (protected visibility), you risk less. Furthermore, you can run validation checks and additional processing against the data you are setting. And what if other developers are working on the project? and are setting the properties directly. And if you look to the right, it seems the site already has a few posts that address this question: Why use getters and setters?

Upvotes: 0

Related Questions