Learn PHP:10-Constants and Magic Constants in PHP

Posted: November 3, 2010 in PHP
Tags:

Constants are named values whose values cannot be changed. When you create a constant you should use all capital letters and underscores separating words to let yourself and others know they are constants. A dollar sign is not needed in front of the name when creating constants. We use the define() function in PHP to create them.

Here is how we create a constant, and use true on the end to make it not worry about letter casing:

 <?php

// define(constant_name, value, case_sensitive=true);
define("AUTHOR_NAME", "Khairul Alam", true);

echo "The person that created this web page is named " . AUTHOR_NAME . ".";

?>
Output is shown at browser like below :

The person that created this web page is named Khairul Alam.

Magic Constants (predefined):

PHP also has predefined magic constants available for you to use. Here we demonstrate a few:

 

 <?php
// __LINE__ Returns the current line number of the file.
echo __LINE__;
echo "<br />";
// __FILE__  Returns the full path and filename of the file. If used inside an include, the name of the included file is returned.
echo __FILE__;
echo "<br />";
// __FUNCTION__  Returns the function name the code is currently executing inside of
echo __FUNCTION__;
echo "<br />";
// __CLASS__ The class name. As of PHP 5 this magic constant returns the class name as it was declared.
echo __CLASS__;
echo "<br />";
?>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s