EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

PHP Magic Constants

Home » Software Development » Software Development Tutorials » PHP Tutorial » PHP Magic Constants

PHP Magic Constants

Introduction to PHP Magic Constants

In PHP Magic Constants, there are in total of eight constants that change their dependency based on where they are used. All these magical constants are resolved at compilation time and not like the constants that we use on a regular basis which we generally resolve at run time. These magical constants are case-insensitive. These constants are predefined constants and start with a double underscore (__) and also ends with a double underscore. These constants are the most practical and most useful constants in PHP. They are simple variables but have a predefined meaning to it. These constants are used to print the user-defined inputs and process the output to display on the screen.

Types of Magic Constants in PHP

There is a total of eight magic constants in PHP mentioned below:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

  • __LINE__: This constant is used to print the line number of the code where it is used on the output screen. It represents the current line number.
  • __FILE__: This constant is used to print the full file path and file name of the file on the output screen.
  • __DIR__: This constant is used to print the full directory path of the particular file on the output screen. It also has one more equivalent method to print the directory path of the file is dirname (__FILE__).
  • __FUNCTION__: This constant will print the function name where it is currently being used on the output screen. If it is used inside the function, then it will print the function name and if it is used outside the function, then it will return a blank.
  • __CLASS__: This constant is used to print the class name where it is used on the output screen. If it is used inside the class, then it will print the class name and if it is used outside the function, then it will return a blank.
  • __TRAIT__: This constant is used where the trait name is used. If it is used inside the function, then it will print the name and if it used outside the function then it will return a blank. The trait is used to print the namespace on the output screen.
  • __METHOD__: This constant is used to print the name of the method defined inside the class where it is used on the output screen. It returns the name of the method that is declared in the code. If it is used inside the method or class, it will return the name of the method and if it is used outside the function, then it will return a blank.
  • __NAMESPACE__: This constant is used to print the name of the current namespace on the output screen.

How Magic Constants Works in PHP?

Below are the examples of How Magic Constants work in PHP:

In PHP, we can use magic constants in a very easy code too difficult ones that we use on our daily basis. Let’s take an example to see how it works:

Example #1

Code:

<!DOCTYPE html>
<html>
<body>
<?php
echo "<h1>Example for __LINE__ constant</h1>";
echo "The line number is " . __LINE__ . "<br><br>";// prints the current line number i.e;7
?>
</body>
</html>

Output:

php magic1

Example #2

Code:

<!DOCTYPE html>
<html>
<body>
<?php
echo "<h2>Example for __FILE__ constant</h2>";
echo __FILE__ . "<br><br>";//prints the full path of the file with extension
?>
</body>
</html>

Output:

php magic2

Example #3

Code:

<!DOCTYPE html>
<html>
<body>
echo "<h3>Example for __DIR__ constant</h3>";
echo __DIR__ . "<br><br>";//prints the full path of the directory where the script is placed.
?>
</body>
</html>

Output:

php magic3

Example #4

Code:

<!DOCTYPE html>
<html>
<body>
<?php
function amount()
{
echo 'the function name is '. __FUNCTION__ . "<br><br>";//the function name is amount.
}
amount();
?>
</body>
</html>

Output:

php magic4

Example #5

Code:

<!DOCTYPE html>
<html>
<body>
<?php
//Using magic constant inside function.
function amount()
{
echo 'the function name is '. __FUNCTION__ . "<br><br>";//the function name is amount.
}
amount();
echo 'the function name is '. __FUNCTION__ ."<br><br>";
?>
</body>
</html>

Output:

php magic5

Example #6

Code:

<!DOCTYPE html>
<html>
<body>
<?php
echo "<h2>Example for __CLASS__</h2>";
class xyz
{
public function __construct() {
;
}
function xyz_method()
{
echo __CLASS__ . "<br>";//prints the name of the class xyz mentioned above.
}
}
$a = new xyz;
$a->xyz_method();
?>
</body>
</html>

Output:

php magic6

Example #7

Code:

<!DOCTYPE html>
<html>
<body>
<?php
class abc
{
function test_abc()
{
echo __CLASS__;//will always print parent class which is abc mentioned above.
}
}
class xyz extends abc
{
public function __vowels()
{
;
}
}
$b = new xyz;
$b->test_abc();
?>
</body>
</html>

Output:

PHP Magic Constants7

Example #8

Code:

<!DOCTYPE html>
<html>
<body>
<?php
echo "<h4>Example for __TRAIT__</h4>";
trait create_trait
{
function trait()
{
echo __TRAIT__;//will print name of the trait create_trait mentioned above.
}
}
class new_class
{
use create_trait;
}
$c = new new_class;
$c-> trait ();
?>
</body>
</html>

Output:

PHP Magic Constants 8

Example #9

Code:

<!DOCTYPE html>
<html>
<body>
<?php
echo "<h2>Example for __METHOD__</h2>";
class method
{
public function __parameter() {
echo __METHOD__ . "<br><br>";//print method::__parameter
}
public function method_fun(){
echo __METHOD__;//print meth::method_fun
}
}
$z = new method;
$z->method_fun();
?>
</body>
</html>

Output:

PHP Magic Constants 9

The output of the respective functions is mentioned above. The line constant will print the current line of the file leela.php stored in the localhost. The file constant will print the file name along with the path as shown in the output. The dir constant or dirname will print the directory path of the current one or the mentioned one. The method and class constant prints the method name and class name mentioned in the code. If the constants are mentioned outside of method and class then it will not print anything on the screen as it is out of the scope and similarly the other constant’s output is mentioned above.

Conclusion

In this article, we learned all the magic constants of PHP and its usage. It can be used in small and tiny programs to big or large programs. These constants can be used by developers for backtracking any issue as where the error might have occurred. These constants will help the developers or users to check on the code as where they are currently present.

Popular Course in this category
PHP Training (5 Courses, 3 Project)5 Online Courses | 3 Hands-on Project | 28+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (5,726 ratings)
Course Price

View Course

Related Courses
Java Servlet Training (6 Courses, 12 Projects)All in One Software Development Bundle (600+ Courses, 50+ projects)

Recommended Articles

This is a guide to PHP Magic Constants. Here we discuss types of magic constants in php and its works in magic constant in php with proper codes and outputs. You can also go through our other related articles to learn more-

  1. Palindrome in PHP
  2. PHP Database Connection
  3. Cookie in PHP
  4. Abstract Class in PHP

PHP Training (5 Courses, 3 Project)

5 Online Courses

3 Hands-on Project

28+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
PHP Tutorial
  • Advanced
    • Overloading in PHP
    • Overriding in PHP
    • Method Overloading in PHP
    • Inheritance in PHP
    • Multiple Inheritance in PHP
    • PHP Interface
    • Encapsulation in PHP
    • PHP Constants
    • PHP Magic Constants
    • PHP Regular Expressions
    • PHP GET Method
    • PHP Annotations
    • PHP Encryption
    • PHP file Functions
    • PHP readfile
    • PHP?Write File
    • PHP Append File
    • PHP Type Hinting
    • PHP Filters
    • PHP Float
    • PHP Form
    • PHP Form Validation
    • Sorting in PHP
    • PHP usort()
    • PHP Stack Trace
    • PHP Stack Overflow
    • PHP Pagination
    • PHP implode
    • Polymorphism in PHP
    • Abstract Class in PHP
    • PHP Final Class
    • PHP Custom Exception
    • error_reporting() in PHP
    • PHP Log Errors
    • Access Modifiers in PHP
    • PHP Change Date Format
    • Static Method in PHP
    • PHP File Handling
    • PHP Output Buffering
    • Get IP Address in PHP
    • Upload a File in PHP
    • String in PHP
    • Public Function in PHP
    • Private in PHP
    • Protected in PHP
    • basename in PHP
    • Validation in PHP
    • PHP mail()
    • PHP Email Form
    • PHP Directory
    • PHP Create Session
    • PHP include_once
    • PHP json_decode
    • PHP XMLWriter
    • PHP XML Reader
    • PHP XML Parser
    • PHP XML into Array
    • Phalcon Framework
  • PHP Basic
    • Introduction To PHP
    • What is PHP
    • PHP Keywords
    • Advantages of PHP
    • Career In PHP
    • Comments in PHP
    • PHP Commands
    • PHP Frameworks
    • PHP Compiler
    • Variables in PHP
    • PHP Superglobal Variables
    • PHP Versions
    • Object in PHP
    • What is Drupal
    • Top PHP Frameworks
    • WebStorm IDE
    • What is phpMyAdmin?
    • PhpStorm
    • Install phpMyAdmin
    • Phalcon Model
  • Data Types
    • PHP Data Types
    • PHP Integer
    • PHP Booleans
  • Operators
    • PHP Operators
    • Arithmetic Operators in PHP
    • Comparison Operators in PHP
    • Logical Operators in PHP
    • Bitwise Operators in PHP
    • Ternary Operator in PHP
    • PHP String Operators
  • Control Statements
    • Control Statement in PHP
    • PHP if Statement
    • if else Statement in PHP
    • elseif in PHP
    • PHP Switch Statement
    • Continue in PHP
    • Break in PHP
  • Loops
    • PHP Loops
    • For Loop in PHP
    • PHP Do While Loop
    • PHP While Loop
    • While Loop in PHP
    • Foreach Loop in PHP
  • Constructor
    • Constructor in PHP
    • Destructor in PHP
  • State Management
    • Cookie in PHP
    • Sessions in PHP
  • Array
    • What is PHP Array
    • Arrays in PHP
    • 2D Arrays in PHP
    • Associative Array in PHP 
    • Multidimensional Array in PHP
    • Indexed Array in PHP
    • PHP Array Functions
    • PHP unset Array
    • PHP Append Array
    • PHP Array Search
    • PHP Split Array
    • PHP array_push()
    • PHP array_pop()
  • Functions
    • Functions in PHP
    • PHP Math Functions
    • PHP Recursive Function
    • PHP String Functions
    • Hashing Function in PHP
    • Date Function in PHP
    • PHP Anonymous Function
    • Calendar in PHP
    • PHP Call Function
    • PHP Pass by Reference
    • PHP ucfirst()
    • PHP ucwords()
    • trim() in PHP
    • isset() Function in PHP
    • PHP replace
    • PHP fpm
    • PHP strpos
    • preg_match in PHP
    • PHP preg_replace()
    • PHP ob_start()
    • PHP Reflection
    • PHP Split String
    • PHP URL
    • PHP preg_match_all
    • PHP strtoupper()
    • PHP preg_split()
    • PHP substr_replace()
    • PHP setlocale()
    • PHP substr_count()
    • PHP Serialize
    • PHP strlen()
    • PHP async
    • PHP Date Time Functions
    • PHP timezone
    • PHP Data Object
    • print_r() in PHP
    • PHP header()
    • PHP strip_tags()
    • PHP chop()
    • PHP MD5()
    • PHP unset()
    • PHP crypt()
    • PHP wordwrap()
    • PHP is_null()
    • PHP strtok()
    • PHP bin2hex()
    • PHP parse_str()
    • PHP levenshtein()
    • PHP addslashes()
    • PHP strtotime
    • PHP sha1()
    • PHP explode()
    • PHP sscanf()
    • PHP require_once
    • PHP Zip Files
    • PHP $_SERVER
    • PHP $_POST
    • PHP Include and Require
    • PHP POST Method
  • Programs
    • Patterns in PHP
    • Star Patterns in PHP
    • Swapping in PHP
    • Fibonacci Series PHP
    • Factorial in PHP
    • Reverse String in PHP
    • Square Root in PHP
    • Random Number Generator in PHP
    • Palindrome in PHP
    • Prime Numbers in PHP
    • Armstrong Number in PHP
    • Socket Programming in PHP
    • Login Page in PHP
    • PHP Login Template
    • PHP Object to String
  • Database
    • PHP Database Connection
    • How to Connect Database to PHP
  • Interview Questions
    • PHP Interview Questions
    • PHP OOP Interview Questions
    • CakePHP Interview Questions
    • Core PHP Interview Questions

Related Courses

PHP Training Course

Java Servlet Training

Software Development Course Training

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - PHP Training (5 Courses, 3 Project) Learn More