PHP 5: Static classes

Static classes are used for utility scripts that (in the past) would have been in common functions or held global variables. The advantage of using a static class is more to increase code readability (and ease of debugging) than for any other reason. A static class may have properties and methods but there will always be only one ‘instance’ (hence static) and any changes will be made ‘globally’.

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

5 thoughts on “PHP 5: Static classes”

  1. An all-static PHP class should have empty private constructor – to prevent creating instances of such class.

  2. Nice post! I have been working on a very basic php framework for some small applications to develop. Using static classes has made things a lot easier and prevents developers from clutering up the global space. thanks again!

Leave a Reply

Your email address will not be published. Required fields are marked *