Home > Tutorials > PHP Tutorials > Understanding PHP Constants

Understanding PHP Constants

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 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.
  • About 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.

    Check Also

    Understanding The <BASE> Tag in 2018

    The <BASE> tag has been a part of HTML for decades now, and little has ...

    Like every other website, this site uses cookies to analyze our traffic. Cookies may also be utilized by our advertisers and partners. By using this website you agree to the use of said cookies. More Information

    The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings, continuing to navigate past this message, or you click "Accept" below then you are consenting to the use of cookies on the Rapid Purple website.