Login |  Register 
I regularly use your site to answer my PHP problems!
Matt
 

Constants

Constants allow a programmer to write a value that is going to remain constant in a way that cannot be changed. This means unlike a variable a constant will always be equal to that value and cannot be assigned to. Therefore you could have a constant called SITENAME, by using the define function which allows constants to be defined.
define('SITENAME', 'PHP Rocks!');
echo SITENAME;
This will output PHP Rocks!. If you write a variable name accidently without a $ sign PHP will assume that you have tried to access a constant so you may get a "Undefined constant" error! As a constant cannot be assigned to, you cannot assign a value to a constant twice. If you do so it will cause a error, to get around this you can used the defined function that will return true if a constant has already been defined.
define('SITENAME', 'PHP Rocks!');
if (!defined('SITENAME'))
{
 define('SITENAME', 'PHP Rocks a lot!');
}
echo SITENAME;
The above code won't error. Note that a constant can contain letters, numbers and underscores but not start with a number. Sometimes you need to return the value of a constant when you only have its name as a string, to do this you use the constant function.
$name = "SITENAME";
echo constant($name);
This will return the value of the constant SITENAME.

Class and Interface constants

Classes and interfaces can also have constants and are visible only via the class or interface. To define a class or interface constant do the following.
//for interfaces
interface People
{
   const CODE = 'Person#';
}
//for classes
class Person
{
    const SPACE = ' ';
}
These can be accessed from within a class like so.
//for classes
class Person
{
    const SPACE = ' ';

    private $firstname;
    private $surname;

    function name()
    {
     return $this->firstname . self::SPACE . $this->surname;
    }
}
From outside the class or interface you can access it like so.
//for classes
echo Person::SPACE;
//for interfaces
echo People::CODE;

Comments to date: 1. Page 1 of 1.
Mell   1:42pm on Saturday, April 4th, 2015
And I was just wodnreing about that too!

security image
Written by Dominic Skinner
Last Updated: 2011-10-25 16:00:38