PHP protected classes and properties, protected from whom?

限于喜欢 提交于 2019-11-28 23:53:32

From yourself!

You use various levels of protection to indicate how you want a class to be used. If a class member is protected or private, it can only be accessed by the class itself. There's no chance you can screw up the value of that member accidentally from "external" code (code outside the class).

Say you have a class member that is only supposed to contain numbers. You make it protected and add a setter which checks that its value can only be numeric:

class Foo {

    protected $num = 0;

    public function setNum($num) {
        if (!is_int($num)) {
            throw new Exception('Not a number!!!');
        }
        $this->num = $num;
    }
}

Now you can be sure that Foo::$num will always contain a number when you want to work with it. You can skip a lot of extra error checking code whenever you want to use it. Any time you try to assign anything but a number to it, you'll get a very loud error message, which makes it very easy to find bugs.

It's a restriction you put on yourself to ease your own work. Because programmers make mistakes. Especially dynamically typed languages like PHP let you silently make a lot of mistakes without you noticing, which turn into very hard to debug, very serious errors later on.

By its very nature, software is very soft and easily degrades into an unmaintainable Rube Goldberg logic machine. OOP, encapsulation, visibility modifiers, type hinting etc are tools PHP gives you to make your code "harder", to express your intent of what you want certain pieces of your code to be and enable PHP to enforce this intent for you.

Protected is not really protecting from anyone to change the source code, but is just a class method visibility in PHP OOP

Class members declared public can be accessed everywhere. Members declared protected can be accessed only within the class itself and by inherited and parent classes. Members declared as private may only be accessed by the class that defines the member.

They mean they are protected in different ways...

  • Private variables are not visible to anywhere except from within the class.
  • Protected variables are not visible to the instantiated object, but are visible to classes which inherit from that class, as well as the class itself.

Nothing stops another programmer from opening a class file and changing the access modifiers.

The hiding of data is a good thing because the less you expose, the more you can control and less bugs you can potentially introduce.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!