Note that __CLASS__ and __METHOD__ both reference the class the code is written in, not whatever the object class is. E.g. if you have an object of class B inheriting from class A, any usage of __CLASS__ in class A is going to give "A".
Ci sono nove costanti magiche che cambiano in base a
dove vengono utilizzate. Per esempio, il valore di
__LINE__
dipende dalla linea che sta
utilizzando nel tuo script. Tutte queste costanti "magiche" vengono risolte
in fase di compilazione, a differenza delle costanti regolari, che vengono risolte in fase di esecuzione.
Queste costanti speciali non fanno distinzione tra maiuscole e minuscole e sono le seguenti:
Nome | Descrizione |
---|---|
__LINE__ |
Il numero della riga corrente del file. |
__FILE__ |
Il percorso completo e il nome del file con i link simbolici risolti. Se utilizzato all'interno di un'inclusione, viene restituito il nome del file incluso. |
__DIR__ |
La cartella del file. Se utilizzato all'interno di un'inclusione,
viene restituita la cartella del file incluso. Questo è equivalente
a dirname(__FILE__) . Il nome della cartella
non ha slash a meno che non sia la directory root.
|
__FUNCTION__ |
Il nome della funzione, o {closure} per le funzioni anonime.
|
__CLASS__ |
Il nome della classe. Il nome della classe include il namespace
in cui è stata dichiarata (es. Foo\Bar ).
Quando usata
in un metodo trait, __CLASS__ è il nome della classe in cui il trait
è usato.
|
__TRAIT__ |
Il nome del trait. Il nome del trait include il namespace
in cui è stato dichiarato (es. Foo\Bar ).
|
__METHOD__ |
Il nome del metodo della classe. |
__NAMESPACE__ |
Il nome del namespace corrente. |
ClassName::class |
Il nome completo della classe. |
Note that __CLASS__ and __METHOD__ both reference the class the code is written in, not whatever the object class is. E.g. if you have an object of class B inheriting from class A, any usage of __CLASS__ in class A is going to give "A".
If PHP is run inside a web server request there is an important difference between the __DIR__ constant and $_SERVER['DOCUMENT_ROOT'].
Where __DIR__ of a PHP script contained within a sub-folder will include the complete server path $_SERVER['DOCUMENT_ROOT'] will contain a server path up to the _root_ of the application. This can be helpful when for instance an auto-loader is defined in an include file sitting inside a sub-folder and where the classes are located in another folder at the root of the application.
<?php
namespace My\App {
class Api {
public static fetch() {
print __FUNCTION__ . "\n"; // outputs fetch
print __METHOD__ . "\n"; // outputs My\App\Api::fetch
}
}
Api::fetch();
}
namespace {
My\App\Api::fetch();
}
?>
__METHOD__ outputs a fully qualified method name; __FUNCTION__ when used in a method, outputs just the method name.