Jun
16
2010

Defining a Constant with PHP

by   |  Posted in Tutorials  |  2 comments

Defining a constant in PHP can come in handy when working with a value that will be used throughout your script. What is a constant exactly? According to PHP.net, “A constant is an identifier (name) for a simple value“. One important thing you need to know is that, like its name states, a constant cannot be changed. That is pretty much the main difference between a constant and a variable.

Here is a basic example:

<?php
define("SITE", "bavotasan.com");
define("AUTHOR", "c.bavota");
 
echo SITE // outputs bavotasan.com
echo AUTHOR // outputs c.bavota
echo SITE." by ".AUTHOR // outputs bavotasan.com by c.bavota
?>

Simple enough. Just remember that constants are case sensitive, so this wouldn’t work:

<?php
echo Site;
?>

Unless, of course, you set a third parameter within the define() function to control the case. By default, it is set to false, which is case-sensitive. To make it case-insensitive, all you need to do is set that third parameter to true.

<?php
define("SITE", "bavotasan.com", true);
 
echo SITE // outputs bavotasan.com
echo Site // outputs bavotasan.com
?>

About the author:

A freelance web developer living in Montreal who spends most of his time writing for this site and building Premium themes for WordPress. You can find him on Twitter @bavotasan.

Site5 Affiliate Link
Share the love...

Tags: , , , , , , , , ,

Short URL: http://bit.ly/cJgs3u

Discussion 2 Comments

  1. SF on August 23, 2010 at 3:50 am

    Is the scope of static variables is the same as regular variable?

  2. Ilyas Kazi on November 2, 2010 at 12:38 am

    Was not aware of 3rd parameter for making case insensitive.. thanks for sharing.