What is the difference between public, private, and protected?

后端 未结 17 1556
抹茶落季
抹茶落季 2020-11-21 07:54

When and why should I use public, private, and protected functions and variables inside a class? What is the difference between them?<

17条回答
  •  南笙
    南笙 (楼主)
    2020-11-21 08:28

    For me, this is the most useful way to understand the three property types:

    Public: Use this when you are OK with this variable being directly accessed and changed from anywhere in your code.

    Example usage from outside of the class:

    $myObject = new MyObject()
    $myObject->publicVar = 'newvalue';
    $pubVar = $myObject->publicVar;
    

    Protected: Use this when you want to force other programmers (and yourself) to use getters/setters outside of the class when accessing and setting variables (but you should be consistent and use the getters and setters inside the class as well). This or private tend to be the default way you should set up all class properties.

    Why? Because if you decide at some point in the future (maybe even in like 5 minutes) that you want to manipulate the value that is returned for that property or do something with it before getting/setting, you can do that without refactoring everywhere you have used it in your project.

    Example usage from outside of the class:

    $myObject = new MyObject()
    $myObject->setProtectedVar('newvalue');
    $protectedVar = $myObject->getProtectedVar();
    

    Private: private properties are very similar to protected properties. But the distinguishing feature/difference is that making it private also makes it inaccessible to child classes without using the parent class's getter or setter.

    So basically, if you are using getters and setters for a property (or if it is used only internally by the parent class and it isn't meant to be accessible anywhere else) you might as well make it private, just to prevent anyone from trying to use it directly and introducing bugs.

    Example usage inside a child class (that extends MyObject):

    $this->setPrivateVar('newvalue');
    $privateVar = $this->getPrivateVar();
    

提交回复
热议问题