Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are member variables usually private?

Tags:

oop

php

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!

like image 912
user784637 Avatar asked Feb 24 '23 10:02

user784637


1 Answers

Rule of thumb is to try to hide information as much as possible, sharing it only when absolutely necessary.

  • Russian coders sometimes say Public Morozov at unnecessarily wide access modifiers, alluding to a story about improper information disclosure and about further punishment caused by that - Pavlik Morozov:

    a 13-year old boy who denounced his father to the authorities and was in turn killed by his family...

like image 131
gnat Avatar answered Mar 05 '23 17:03

gnat