Why are member variables usually private?

2019-05-11 23:59发布

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!

标签: php oop
7条回答
叛逆
2楼-- · 2019-05-12 00:34

It's to prevent properties from being directly manipulated from the outside and possibly putting the object into an inconsistent state.

One of the fundamentals of OOP is that an object should be responsible for maintaining its own state and keeping it internally consistant, for example not allowing a property that's only meant to hold positive integers from being set to -343.239 or making sure an internal array is structured properly. A sure fire way of doing this is make it impossible for the values of properties to be directly set from the outside. By making the property private, you're preventing outside code from manipulating it directly, forcing it to go through a setter method that you have written for the job. This setter can do checks that the proposed change won't put the object into an inconsistent state and prevent any changes that would.

Most books and examples aimed at beginners tend to use very simple objects so it may not make sense as to why you need to go through all the private properties and getters and setters molarchy, but as the complexity of an object increases, the benefits become increasingly obvious. Unfortunately, complex objects are also not much good as teaching aids for beginners, so this point can be easily lost at first.

查看更多
登录 后发表回答