User Contributed Notes 22 notes

class Item{/** * This is INSIDE CODE because it is written INSIDE the class. */public $label; public $price;}

/** * This is OUTSIDE CODE because it is written OUTSIDE the class. */$item = new Item();$item->label = 'Ink-Jet Tatoo Gun';$item->price = 49.99;

?>

Ok, that's simple enough... I got it inside and out. The big problem with this is that the Item class is COMPLETELY IGNORANT in the following ways:* It REQUIRES OUTSIDE CODE to do all the work AND to know what and how to do it -- huge mistake.* OUTSIDE CODE can cast Item properties to any other PHP types (booleans, integers, floats, strings, arrays, and objects etc.) -- another huge mistake.

Note: we did it correctly above, but what if someone made an array for $price? FYI: PHP has no clue what we mean by an Item, especially by the terms of our class definition above. To PHP, our Item is something with two properties (mutable in every way) and that's it. As far as PHP is concerned, we can pack the entire set of Britannica Encyclopedias into the price slot. When that happens, we no longer have what we expect an Item to be.

INSIDE CODE should keep the integrity of the object. For example, our class definition should keep $label a string and $price a float -- which means only strings can come IN and OUT of the class for label, and only floats can come IN and OUT of the class for price.

<?php

class Item{/** * Here's the new INSIDE CODE and the Rules to follow: * * 1. STOP ACCESS to properties via $item->label and $item->price, * by using the protected keyword. * 2. FORCE the use of public functions. * 3. ONLY strings are allowed IN & OUT of this class for $label * via the getLabel and setLabel functions. * 4. ONLY floats are allowed IN & OUT of this class for $price * via the getPrice and setPrice functions. */

public function setLabel($label) // Rule 2 - public function.{/** * Make sure $label is a PHP string that can be used in a SORTING * alogorithm, NOT a boolean, number, array, or object that can't * properly sort -- AND to make sure that the getLabel() function * ALWAYS returns a genuine PHP string. * * Using a RegExp would improve this function, however, the main * point is the one made above. */

public function setPrice($price) // Rule 2 - public function.{/** * Make sure $price is a PHP float so that it can be used in a * NUMERICAL CALCULATION. Do not accept boolean, string, array or * some other object that can't be included in a simple calculation. * This will ensure that the getPrice() function ALWAYS returns an * authentic, genuine, full-flavored PHP number and nothing but. * * Checking for positive values may improve this function, * however, the main point is the one made above. */

Now there is nothing OUTSIDE CODE can do to obscure the INSIDES of an Item. In other words, every instance of Item will always look and behave like any other Item complete with a label and a price, AND you can group them together and they will interact without disruption. Even though there is room for improvement, the basics are there, and PHP will not hassle you... which means you can keep your hair!

If you have problems with overriding private methods in extended classes, read this:)

The manual says that "Private limits visibility only to the class that defines the item". That means extended children classes do not see the private methods of parent class and vice versa also.

As a result, parents and children can have different implementations of the "same" private methods, depending on where you call them (e.g. parent or child class instance). Why? Because private methods are visible only for the class that defines them and the child class does not see the parent's private methods. If the child doesn't see the parent's private methods, the child can't override them. Scopes are different. In other words -- each class has a private set of private variables that no-one else has access to.

A sample demonstrating the percularities of private methods when extending classes:

As far as it regards the properties of objects, visibility is, yes, as the examples show.Private, protected methods are not accessible via syntax $a->protectedVar, however their values are still (php 5.3.26) accessible through a number of other methods (serializing, converting to array, and nevertheless using the ReflectionClass methods).As it was pointed out and such as in the example below:<?php

This has already been noted here, but there was no clear example. Methods defined in a parent class can NOT access private methods defined in a class which inherits from them. They can access protected, though.

After having the how explained, many people will still be left wondering about the why. How should the different kinds of visibility be used in practice?

Some kind of labelling for the public and private parts of an interface is certainly necessary. We need to be clear which methods will be part of the public interface and which are only used internally .

In older versions of php notionally-private functions were prefixed with an underscore - a much simpler and more elegant solution to the labelling problem. "Protected" adds clutter which affects readability. It adds a lot of unnecessary typing to what is already a keyboard-intensive job.

As for enforcement.. no-one ever got mixed up about public/private so long as they were clearly labelled. As such, "protected" is an attempt to solve a problem which simply did not exist.

Private is even worse. It specifically encourages bad object-oriented code with the use of inheritance in places where you should be thinking about separate, co-operating objects.

A feeling that classes which inherit from each other need to hide some of their bits from each other is a sure sign that you need to break the code up into separate objects. This is exactly what encapsulation is for. It doesn't make any sense to try to encapsulate bits inside an inheritance tree. Classes which extend other classes must always be free to override whatever it is they need to override in their parent classes.

In short, use protected if you must, do not use private at all. Do not try to squeeze too much new functionality into an inheritance tree: create networks of co-operating objects with clearly-defined responsibilities instead.

It's a real shame that php took the decision to implement private and protected. They add nothing to our ability to write good quality OO code; they simply make that code more difficult to write and to understand. Clarity and simplicity are incredibly important in programming but now both php programmers and php developers are stuck with these unnecessary layers of complexity.

"$this->private" is only in A private. If you write it in class B it's a runtime declaration of the public variable "$this->private", and PHP doesn't even warn you that you create a variable in a class without declaration, because this is normal behavior.

Just wanted to share a trap for the unwary. Where there are several layers of object assignments, setting the bottom object's properties as private will prevent its exposure. However, if the bottom object has public properties, intermediate objects which are themselves set as private but are derived from the bottom object can inadvertently be exposed to updates.

If you miss the "package" keyword in PHP in order to allow access between certain classes without their members being public, you can utilize the fact, that in PHP the protected keyword allows access to both subclasses and superclasses.

I want to merge notes from different comments about visibility of class members from parent class / sibling class point of view because visibility rules are similar. Here are main points: 1. Methods declared in parent class can access some child class members. 2. Class can access some sibling class members using methods declared in common parent. NB: only inherited not-overridden parent method could be used, if you override it in current class you have to call parent method statically to get access to sibling members.