Page 191 - Open Soource Technologies 304.indd
P. 191
Unit 8: Objects
Notes
<?php
class User
{
const DefaultUsername = “John Doe”;
const MinimumPasswordLength = 6;
}
echo “The default username is “ . User::DefaultUsername;
echo “The minimum password length is “ . User::MinimumPasswordLength;
?>
As you can see, it is much like declaring variables, except there is no access modifier—a constant
is always publically available. As required, we immediately assign a value to the constants,
which will then stay the same all through execution of the script. To use the constant, we write
the name of the class, followed by the double-colon operator and then the name of the constant.
That’s really all there is to it.
Develop a PHP program to show the static classes.
8.5.7 The “final” Keywords
We know how we could let a class inherit from another class. We also know how you could
override a function in an inherited class, to replace the behaviour originally provided. However,
in some cases you may want to prevent a class from being inherited from or a function to be
overridden. This can be done with the final keyword, which simply causes PHP to throw an
error if anyone tries to extend your final class or override your final function.
A final class could look like this:
final class Animal
{
public $name;
}
A class with a final function could look like this:
class Animal
{
final public function Greet()
{
return “The final word!”;
}
}
LOVELY PROFESSIONAL UNIVERSITY 185