Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
905 views
in Technique[技术] by (71.8m points)

oop - PHP protected classes and properties, protected from whom?

I'm just getting started with OOP PHP with PHP Object-Oriented Solutions by David Powers, and am a little curious about the notion of protection in OOP.

The author clearly explains how protection works, but the bit about not wanting others to be able to change properties falls a bit flat. I'm having a hard time imagining a situation where it is ever possible to prevent others from altering your classes, since they could just open up your class.php and manually tweak whatever they pleased seeing as how PHP is always in plain text.

Caution: all of the above written by a beginner with a beginner's understanding of programming.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...