js

Friday, December 15, 2023

Explain magic constants in php

 Q. Explain magic constants in php
Answer:

In PHP, magic constants are predefined constants that change based on their usage context. They are called "magic" because they provide information about various aspects of the script execution, file, or other program elements without explicitly being declared.


Here are some commonly used magic constants in PHP:


__LINE__: The current line number of the file.
echo 'This is line ' . __LINE__;

__FILE__: The full path and filename of the file. If used inside an include, it will return the included file name.

echo 'This file is: ' . __FILE__;

__DIR__: The directory of the file.
echo 'This file is in the directory: ' . __DIR__;

__FUNCTION__: The name of the current function.
function example() {
    echo 'This function is: ' . __FUNCTION__;
}


__CLASS__: The name of the current class.
class MyClass {
    public function showClassName() {
        echo 'This class is: ' . __CLASS__;
    }
}


__METHOD__: The name of the current class method.
class MyClass {
    public function showMethodName() {
        echo 'This method is: ' . __METHOD__;
    }
}


__NAMESPACE__: The name of the current namespace.
namespace MyNamespace;

echo 'This namespace is: ' . __NAMESPACE__;


These constants are automatically populated by the PHP interpreter and provide useful information about the context in which they are used.

No comments:

Post a Comment

SEBA HSLC Question Paper Assamese 2022