Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The advantage / disadvantage of private variables?

I'm used to make pretty much all of my class variables private and create "wrapper" functions that get / set them:

class Something{
  private $var;

  function getVar(){
    $return $this->var;
  }

}

$smth = new Something();
echo $smth->getVar();

I see that a lot of people do this, so I ended up doing the same :)

Is there any advantage using them this way versus:

class Something{
  public $var;
}
$smth = new Something();
echp $smth->var;

?

I know that private means that you can't access them directly outside the class, but for me it doesn't seem very important if the variable is accessible from anywhere...

So is there any other hidden advantage that I missing with private variables?

like image 336
Alex Avatar asked Jun 05 '11 12:06

Alex


People also ask

Why are private variables useful?

By making the variable a private data member, you can more easily ensure that the value is never negative. On the other hand, if the variable is public, another class could change it to a negative value which can cause other parts of the code to crash.

What is a private variable?

In general, private variables are those variables that can be visible and accessible only within the class they belong to and not outside the class or any other class. These variables are used to access the values whenever the program runs that is used to keep the data hidden from other classes.

What are the benefits of a private class in Java?

In Summary private keyword in java allows most restrictive access to variables and methods and offer strongest form of Encapsulation. private members are not accessible outside the class and private method can not be overridden.


1 Answers

It's called encapsulation and it's a very good thing. Encapsulation insulates your class from other classes mucking about with it's internals, they only get the access that you allow through your methods. It also protects them from changes that you may make to the class internals. Without encapsulation if you make a change to a variable's name or usage, that change propagates to all other classes that use the variable. If you force them to go through a method, there's at least a chance that you'll be able to handle the change in the method and protect the other classes from the change.

like image 109
tvanfosson Avatar answered Sep 28 '22 14:09

tvanfosson