Class Constants
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, double-colon operator are
used to access a class constant. Here is a basic example:
<?php
class
User
{
const DefaultUsername = "Imran Khan";
const MinimumPasswordLength = 6;
}
echo
"The default username is " . User::DefaultUsername;
echo
"The minimum password length is " . User::MinimumPasswordLength;
?>
Constants can be defined for some basic expressions whose
values are always going to remain the same.
For example, defining constant using math expression:
<?php
class MyTimer {
const SEC_PER_DAY = 60 * 60 * 24;
}
?>
class MyTimer {
const SEC_PER_DAY = 60 * 60 * 24;
}
?>
Class
constant can also be defined with an array. An example of such declaration is
given below:
<?php
class MyClass
{
const ABC = array('A', 'B', 'C');
const A = '1';
const B = '2';
const C = '3';
}
var_dump(MyClass::ABC);
class MyClass
{
const ABC = array('A', 'B', 'C');
const A = '1';
const B = '2';
const C = '3';
}
var_dump(MyClass::ABC);
As it is clear that it's 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 program. To use the constant, we
write the name of the class, followed by the double-colon operator and then the
name of the constant.
No comments:
Post a Comment