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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…