PHP 5: Static classes

Static classes are often used for algorithms that may be used by multiple classes. They may also be used to construct objects of a specific type and to abstract logic from classes (to encourage loose coupling of objects – i.e. the ability of one class to operate without dependency on another). The example that follows allows the passing in of a username and password and will decide which class of user to instantiate and return. This is important in the case where we want to create a User object, but we have now defined the User class as abstract – how do we know what class of User to create?
class UserHandling
{
public static $numUsers = 0;
//a static class has no constructor
/*
This static method accepts a username and password
and returns an object of type User
*/
static public function makeUser($username,$password)
{
/*
Logic in here to look in a database
and get a userTypeID based on username and
password
*/
if($isValidUser)
{
if($isAdmin)
{
$user = new AdminUser();
}
else
{
$user = new RegisteredUser();
}
}
else
{
$user = new UnregisteredUser();
}
UserHandling::$numUsers++;
//Changing a static variable
//inside the class still
//needs the full reference.
//There is no “$this” inside a
//static class.
return $user;
}
}
//To make a user object, from anywhere in the code
$user = UserHandling::makeUser($username,$password);
Properties accessed from outside a static class (if they’re public) are also handled in the same way:
echo UserHandling::$numUsers;
Next section: Interfaces
Comments:
public $numusers
ought to be
public static $numusers
You do not need the whole scope, just use the self-keyword.
An all-static PHP class should have empty private constructor - to prevent creating instances of such class.


