I just started to learn object oriented programming today and just by observation noticed that in all examples, member variables are private. Why is that usually the case?
// Class
class Building {
// Object variables/properties
private $number_of_floors = 5; // These buildings have 5 floors
private $color;
// Class constructor
public function __construct($paint) {
$this->color = $paint;
}
public function describe() {
printf('This building has %d floors. It is %s in color.',
$this->number_of_floors,
$this->color
);
}
}
Also, if you declare the member variable to be public, what is the syntax for accessing it outside of the class it was declared in?
And finally, do you have to prepend "public" or "private" to every variable and function inside a class?
EDIT: Thanks all for your answers, can anyone please confirm if you have to prepend "public" or "private" to every variable and function inside a class?
Thanks!
Private variables can't be accessed from outside, that gives you control.
But if you put them Public then you can access it lke this
For example
but you have to put your number_of_floors variable to public, if you want to access private member then you need to implement new method in Building class
so your code should look like this
Making variables private keeps calling code from depending on the implementation details of your class so you can change the implementation afterward without breaking the calling code.
You can declare more than one variable on the same line and only use
private
orpublic
once:See also PHP docs' "Classes and Objects".
I really dont know how to answer such question, but i describe u the best as per php manual
Property Visibility
for more information see Visibility
Senad's answer is correct in that it is good programming practice to make variables you do not want exterior methods to access private.
However, the reasoning for it in memory managed/garbage collected languages is that when you maintain a reference to an object, it is not able to be garbage collected, and can cause memory leaks.
Hope this helps!
Rule of thumb is to try to hide information as much as possible, sharing it only when absolutely necessary.
It's to make the coding easier for you, and to make you less likely to make mistakes. The idea is that only the class can access its private variables, so no other classes elsewhere in your code can interfere and mess something up by changing the private variables in unexpected ways. Writing code like this, with a bunch of autonomous classes interacting through a small number of strictly controlled public methods, seems to be an easier way to code. Big projects are much easier to understand because they are broken up into bite sized chunks.