Page 190 - Open Soource Technologies 304.indd
P. 190
Web Technologies-I
Notes 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. We admit that the validation being performed here is very limited, but obviously it
can be expanded. Now, could not 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 do not 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 is basically the same.
A static method cannot access non-static variables and methods, since these
require an instance of the class.
8.5.6 Class Constants
A constant is, just like the name implies, a variable that can never be changed. When you declare
a constant, you assign a value to it, and after that, the value will never change. Normally, simple
variables are just easier to use, but in certain cases constants are preferable, for instance to signal
to other programmers (or your self, in case you forget) that this specific value should not be
changed during runtime.
Class constants are just like regular constants, except for the fact that they are declared on a
class and therefore also accessed through this specific class. Just like with static members, you
use the double-colon operator to access a class constant. Here is a basic example:
184 LOVELY PROFESSIONAL UNIVERSITY