Search code examples
phpoopencapsulation

Should I use private keyword or public keyword in getter/setter?


I'm still learning in OOP. I have one concern that using private keyword that using in Getter and Setter. Based on my understanding about private keyword, it can't access from outside the class. Here a snippet that copy from a book!

<?php
//GetSet.php
class GetSet
{
     private $dataWarehouse;
     function __construct()
     {
         $this->setter(200);
         $got= $this->getter();
         echo $got;
     }

     private function getter()
     {
         return $this->dataWarehouse;
     }

     private function setter($setValue)
     {
          $this->dataWarehouse=$setValue;
     }
}

$worker=new GetSet();

?>

But, I saw a lot of that using public keyword in Getter and Setter. So, the book said that "if we use public keyword in Getter and Setter, it can break encapsulation concept" .

My question is "Should I use public or private keyword in Getter and Setter? or Is this based on business requirement?".


Solution

  • If you have sufficient getter and setter methods for that variable, I would make it private to be more secure.

    This programmer's question also makes some other practical arguments for using private variables.

    A public member can be accessed from outside the class, which for practical considerations means "potentially anywhere". If something goes wrong with a public field, the culprit can be anywhere, and so in order to track down the bug, you may have to look at quite a lot of code.

    A private member, by contrast, can only be accessed from inside the same class, so if something goes wrong with that, there is usually only one source file to look at. If you have a million lines of code in your project, but your classes are kept small, this can reduce your bug tracking effort by a factor of 1000.