Static classes
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:
<?php 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; else return false; } } $password = "test"; if(User::ValidatePassword($password)) echo "Password is valid!"; else 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.
© php5-tutorial.com 2007-2012