You are currently viewing What are the Magic Constants in PHP | Full Guide
  • Post category:PHP

What are the Magic Constants in PHP | Full Guide

Magic Constants in PHP

In this article, we will discuss What is magic constants in PHP.

What are magic constants in PHP

A magic constant is a predefined constant that changes its value depending on the context in which it is used. There are nine magic constants available in php

  1. __LINE__ – If you use an echo statement, it returns the current line number.
  2. __FILE__ – It returns the full path of the file with .php extension
  3. __DIR__ – The DIR magic constant returns the full directory path of the executed file.
  4. __FUNCTION__ – If you use this magic constant out of the funciton, it will return a blank. If you use it inside the function, it will return the function name.
  5. __CLASS__ – You should use the CLASS magic constant inside the class within the function, it returns the class name. If you have multiple classes, it returns the parent class name.
  6. __TRAIT__ – This magic constant return the trait name. You should use this magic constant inside the trait within the function.
  7. __METHOD__ – It returns method name.
  8. __NAMESPACE__ – The NAMESPACE magic constant returns the current namespace where it is used.

1. Example for LINE

<?php;
// It print your current line number
echo "You are at line number " . __LINE__ .;
?>

Output:

You are at line number 3

2. Example for FILE

<?php
//It print your full path of file with .php extension
echo __FILE__ . ;
?>

Output:

D:\xampp\htdocs\program\magic.php

3. Example for DIR

<?php
//print full path of directory where script will be placed
echo __DIR__ . ;
?>

Output:

READ ALSO  How do we Create PHP Constructor Function

D:\xampp\htdocs\program

4. Example for FUNCTION

<?php
function run(){
//print the function name i.e; run
echo 'The function name is '. __FUNCTION__ .;
}
run();
?>

Output:

The function name is run

5. Example for CLASS

<?php
class parent
{
function getClassName(){
//printing class name using magic constant
echo __CLASS__ .;
}
}
$t = new parent;
$t->getClassName();
?>

Output:

parent

6. Example for TRAIT

<?php
trait main_trait{
function sample(){
//printimg trait name using TRAIT magic constant
echo __TRAIT__;
}
}
class Company {
use main_trait;
}
$a = new Company;
$a->sample();
?>

Output:

trait name: main_trait

7. Example for TRAIT

<?php
class method {
public function __construct() {
//printing method name using METHOD magic construct
echo __METHOD__ . ;
}
?>

Output:

method name : construct

8. Example for NAMESPACE

<?php
class name {
public function __construct() {
echo 'This line will print on calling namespace.';
}
}
$class_name = __NAMESPACE__ . '\name';
$a = new class_name;
?>

Output:

This line will print on calling namespace.

Leave a Reply