WikiGalaxy

Personalize

PHP Magic Constants

Introduction to PHP Magic Constants

__LINE__

The __LINE__ magic constant returns the current line number of the file. It is useful for debugging purposes, allowing developers to track the execution flow within the script.

__FILE__

The __FILE__ magic constant returns the full path and filename of the file. This is particularly useful for including files relative to the current script's directory.

__DIR__

The __DIR__ magic constant returns the directory of the file. It is often used to include or require files in the same directory, ensuring portability across different environments.

__FUNCTION__

The __FUNCTION__ magic constant returns the name of the function where it is used. This can be helpful for logging or debugging function calls.

__CLASS__

The __CLASS__ magic constant returns the name of the class where it is used. It is beneficial for dynamic class handling and introspection.

__TRAIT__

The __TRAIT__ magic constant returns the name of the trait where it is used. This is useful when working with traits in PHP, providing context about the trait in use.


<?php
echo "This is line number " . __LINE__ . "\n";
echo "This file is located at " . __FILE__ . "\n";
echo "This directory is " . __DIR__ . "\n";

function testFunction() {
    echo "This function is called " . __FUNCTION__ . "\n";
}

class TestClass {
    function displayClassName() {
        echo "This class is called " . __CLASS__ . "\n";
    }
}

trait TestTrait {
    function displayTraitName() {
        echo "This trait is called " . __TRAIT__ . "\n";
    }
}

testFunction();
$test = new TestClass();
$test->displayClassName();

class UseTrait {
    use TestTrait;
}

$traitTest = new UseTrait();
$traitTest->displayTraitName();
?>
    

__METHOD__

The __METHOD__ magic constant returns the name of the class method where it is used. It is useful for logging and debugging method calls.

__NAMESPACE__

The __NAMESPACE__ magic constant returns the name of the current namespace. This is crucial for managing code organization and avoiding name conflicts in larger projects.

logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025