Help Explain "Visibility" To Me?

Hello all. Im relatively new to OOP but picking up the methodologies quickly and have begun planning my first PHP/mySQL application. For some reason I cant seem to completely grasp the idea of “visibility”. I read definitions in books and tutorials and see it in action and it just wont sink in. I understand denoting a property as “public” means its available to the outside world. “Private” and “Protected” mean its not available. What exactly does that mean? Anyone have any simple examples/analogies that could help me understand this? Thanks!

It’s about encapsulation

public anyone can access it
protected only descendants can access it
private only you can access it

depending how access modifiers are defined, other coders will extend your classes, inherit methods or instance variables

Visibility

If you have a property of a class marked as public:


class foo {
public bar;

function setBar( $var ){

if( $var < 11 ){
$this->Bar = $var ;
return true ;
}

return false ;
}

function addToBar( $var ){

$val = $this->bar + $var ;

if( $val > 20 ){

Throw UpException();

}

return $val ;
}
// and so on

}


It means that someone, maybe even you accidentally, can do this:

$kk = new foo ;
$kk->bar = 10000000 ;

So by passing your setter and getters and the rule you had encapsulated and applied for presumably some sound reason.

There may be times you wish to have an object which contains just variables like this of course.

A long time ago I had a computer science instructor describe the difference as follows.

Think of yourself. The public you is what anyone sees - basically you fully clothed. Protected is how your children might see you - unshaven, in bathrobes, a towel, boxers or the like. Private - well you see yourself in the mirror like that - and there’s no spouse keyword :smiley:

The purpose of visibility is to limit contact between code sections. Programming projects become more complex over time in a progression of K(n) - a complete graph.

That is, for each n components, there are K things to test. 5 components have a total of 15 things to test (5 nodes and 10 lines of contact). It’s an exponential growth.

By limiting visibility the connection points are pruned. Consider our program with 5 components. If 1 of the components can only touch 1 other component then we’ve reduced K to 11.

At the end of the day the principle goal of MVC patterns and the like is reduction of these points of contact in order to keep the code testable and manageable.

Visibility is a tool of this approach. The fewer the public properties and methods of a class there are, the easier it is to test it. Similarly, private limits the polymorphism of the class and makes the testing of child classes easier.