A constant within PHP is essentially an identifier for a simple value, and unlike a variable, the value of a constant cannoyt be changed after it is declared. By default a constant is case-sensitive; and most people tend to give constant identifiers uppercase names. To get started you will want to define a constant using the define() function, like so:

define("SITENAME", "My Website Name & Description");

You will need to use the define() function every time you wish to set a new PHP constant. Unlike PHP variables constants cannot be defined by simple assignment. Once you have properly defined SITENAME you can use the SITENAME constant whenever we wish to display our website name and description, saving us on having to do tons of extra typing. This can be done in one of two ways. You can either simply echo the constant name, or use the constant() function. The results are the same.

echo SITENAME; 
echo constant("SITENAME");

Take note, only scalar data such as a boolean, integer, float or a string can be contained in a constant. Furthermore constants may be defined and accessed anywhere without regard to variable scope rules.

PHP also has a series of built-in constants that can be accessed within any PHP script you write. Each one of these constants returns something specific about the script/file it is used in:

  • __LINE__: Returns the current line number of the file.
  • __FILE__: Returns the full path and filename of the file. Take note that since PHP 4.0.2 __FILE__ includes an absolute path.
  • __FUNCTION__: Returns the declared functions name.
  • __CLASS__: Returns the class name as it was declared.
  • __METHOD__: Returns the class method name, as it was declared.
  • Published by Michael Boguslavskiy

    Michael Boguslavskiy is a full-stack developer & online presence consultant based out of New York City. He's been offering freelance marketing & development services for over a decade. He currently manages Rapid Purple - and online webmaster resources center; and Media Explode - a full service marketing agency.

    Join the Conversation

    1 Comment

    Leave a comment

    Your email address will not be published. Required fields are marked *