Thursday, March 19, 2009

Magic constants in php

In php there are many predefined constants. Normal constant value is not changed but out of the many predefined constants seven constants value are changed based on the usage inside the script. These seven constants are called magic constants.

Their description are as below.

1)__LINE__ : This constant prints the current line number of the file.

2)__FILE__ : __FILE__ prints the absolute path of the file. If it is used inside an include, the name of the included file is returned.

3)__DIR__ : It prints the directory name of the file. If used inside an include, the directory of the included file is returned. Note that trailing slash is not there without unix root (/) directory.

4)__FUNCTION__ : It returns the function name. In PHP 5 it is case sensitive but in PHP version 4 its value was always lowercased.

5)__CLASS__ : It returns the class name. In PHP 5 it is case sensitive but in PHP version 4 its value was always lowercased.

6)__METHOD__ : It prints the class method name.

7)__NAMESPACE__ : It returns the name of the current namespace (case-sensitive). This constant is defined in compile-time (Added in PHP 5.3.0).

Code

<html>
<body>
<?php
echo "This example will show about magic constants." ;
echo "<br />";
echo "This is line number: ". __LINE__;
echo "<br />";
echo "This is file name: ". __FILE__;
echo "<br />";

class MyBaseClass
{
function function_a()
{
echo "A function called -" . __CLASS__ . "<br/>";
}

function function_b()
{
echo "B function called -" . get_class($this) . "<br/>";
}

}

class MyDerivedClass extends MyBaseClass
{
function function_a()
{
parent::function_a();
echo "A function called --" . __CLASS__ . "<br/>";
}

function function_b()
{
parent::function_b();
echo "B function called --" . get_class($this) . "<br/>";
echo "This is a function: " .__FUNCTION__ ."<br/ >";
}
}

$object_b = new MyDerivedClass();

$object_b->function_a();
echo "<br/>";
$object_b->function_b();
echo "<br />";
echo "<br />";
?>
</body>
</html>


Output
This example will show about magic constants.
This is line number: 6
This is file name: C:\apache2triad\htdocs\magic_constants.php
A function called -MyBaseClass
A function called --MyDerivedClass

B function called -MyDerivedClass
B function called --MyDerivedClass
This is a function: function_b

Related Documents
Working with cookie in php(set, retrieve, delete)
Accessing data from html forms in php
Track error messages on php
Array declaration, assignment and printing in php
Variables in PHP
Constants in php

No comments:

Post a Comment