concept private method in category php

appears as: private methods
PHP in Action: Objects, Design, Agility

This is an excerpt from Manning's book PHP in Action: Objects, Design, Agility.

Finding faults with a programming language is easy. If it lacks a feature you desperately feel you need, you can use that as a reason to put it down. If it has a feature you think is totally unnecessary, you can frown upon that. PHP 4 had no visibility constraints such as private methods; this of course was a Bad Thing to programmers who were used to languages such as C++ and Java. PHP 5 has visibility constraints, and I'm sure there are others—who are accustomed to other languages that lack these features—who find this appalling.

Private methods and variables are available only from within the same class. Protected methods and variables are available from within the same class and from parent and child (or more precisely, ancestor and descendant) classes.

3.1.2. When to use private methods

Private methods are often utility methods that are used repeatedly in a class (but not in any other class) or methods that are used only in one place. It might seem odd to have a separate method for something that happens in only one place, but the reason for this is typically readability: putting a chunk of code into a separate method that has an intention-revealing name.

Listing 3.1. UserValidator class using private methods for readability
class UserValidator { function validateFullUser($user) { if ($this->nameUnchanged($user) || $this->nameNotInDB()) return TRUE; return FALSE; } private function nameUnchanged($user) { return $_POST['username'] == $user->getUsername(); } private function nameNotInDB() { // Query the database, return TRUE if there is no user // with a name corresponding to $_POST['username']) } }