Static classes

Since a class can be instantiated more than once, it means that the values it holds, are unique to the instance/object and not the class itself. This also means that you can't use methods or variables on a class without instantiating it first, but there is an exception to this rule. Both variables and methods on a class can be declared as static (also referred to as "shared" in some programming languages), which means that they can be used without instantiating the class first. Since this means that a class variable can be accessed without a specific instance, it also means that there will only be one version of this variable. Another consequence is that a static method cannot access non-static variables and methods, since these require an instance of the class.

In a previous chapter, we wrote a User class. Let's expand it with some static functionality, to see what the fuzz is all about:
class User
    public $name;
    public $age;
    public static $minimumPasswordLength = 6;
    public function Describe()
        return $this->name . " is " . $this->age . " years old";
    public static function ValidatePassword($password)
        if(strlen($password) >= self::$minimumPasswordLength)
            return true;
            return false;

$password = "test";
    echo "Password is valid!";
    echo "Password is NOT valid!";
What we have done to the class, is adding a single static variable, the $minimumPasswordLength which we set to 6, and then we have added a static function to validate whether a given password is valid. I admit that the validation being performed here is very limited, but obviously it can be expanded. Now, couldn't we just do this as a regular variable and function on the class? Sure we could, but it simply makes more sense to do this statically, since we don't use information specific to one user - the functionality is general, so there's no need to have to instantiate the class to use it.

As you can see, to access our static variable from our static method, we prefix it with the self keyword, which is like this but for accessing static members and constants. Obviously it only works inside the class, so to call the ValidatePassword() function from outside the class, we use the name of the class. You will also notice that accessing static members require the double-colon operator instead of the -> operator, but other than that, it's basically the same.
^ Back to Top