phpday 2027 - Call for Papers

Constantes Mágicas

Constantes mágicas são palavras-chave que são substituídas por informações sobre sua própria localização no código-fonte: seu arquivo e linha, e a função, classe, trait, namespace ou propriedade que as envolve. Apesar do nome, elas não são constantes reais: defined() e constant() não as reconhecem, e uma constante com o mesmo nome criada com define() não as afeta. Elas não diferenciam maiúsculas de minúsculas. Quando usadas fora do contexto relevante (por exemplo, __CLASS__ fora de uma classe), elas são substituídas por uma string vazia.

Constantes mágicas do PHP
Nome Descrição
__LINE__ O número da linha em que está escrita.
__FILE__ O caminho completo e o nome do arquivo em que está escrita, com links simbólicos resolvidos.
__DIR__ O diretório do arquivo, equivalente a dirname(__FILE__). Não possui barra final a menos que seja o diretório raiz.
__FUNCTION__ O nome da função em que está escrita, incluindo seu namespace (por exemplo, Foo\bar). Dentro de um método, apenas o nome do método. Para funções anônimas, um nome gerado pelo mecanismo que inclui onde o closure foi definido (a partir do PHP 8.4.0; anteriormente {closure}).
__CLASS__ O nome da classe em que está escrita, incluindo seu namespace (por exemplo, Foo\Bar). Dentro de um trait, o nome da classe que usa o trait. Para classes anônimas, um nome gerado pelo mecanismo. Para obter o nome da classe em que um método foi chamado, use static::class.
__TRAIT__ O nome do trait, incluindo seu namespace (por exemplo, Foo\Bar).
__METHOD__ O nome da classe e do método em que está escrita (por exemplo, Foo\Bar::baz). Dentro de um trait, o nome do trait é usado em vez do nome da classe. Fora de um método, o mesmo que __FUNCTION__.
__PROPERTY__ O nome da propriedade, quando usada dentro de um gancho de propriedade. Disponível a partir do PHP 8.4.0.
__NAMESPACE__ O nome do namespace atual.

Exemplo #1 Usando constantes mágicas

<?php
namespace App;

function helper()
{
    echo __FUNCTION__, "\n";
    echo __METHOD__, "\n";
}

trait Greets
{
    public function greet()
    {
        echo __CLASS__, "\n";
        echo __TRAIT__, "\n";
        echo __METHOD__, "\n";
        echo __FUNCTION__, "\n";
    }
}

class Greeter
{
    use Greets;
}

helper();
(new Greeter)->greet();
echo __NAMESPACE__, "\n";

O exemplo acima produzirá:

App\helper
App\helper
App\Greeter
App\Greets
App\Greets::greet
greet
App

Notas de Usuários 5 notes

up
1
Athralon dot media at gmail dot com
7 months ago
This is a magic constant: "but what is the relative path?"
up
2
theking2 at king dot ma
4 years ago
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.
up
0
webmaster at event-horizon dot lt
8 months ago
I have got this script:
<?=
$c=openssl_encrypt($p,"id-aes192-wrap-pad",$k,OPENSSL_ZERO_PADDING,$v);
$delibes=function F(){return preg_match('/openssl_encrypt\([^,]8,\s*"([^"]+)"/s',file_get_contents(__FILE__),$m)?$m[1]:null;}
// Usage:
// echo $GLOBALS['delibes']
// Note-to-self: The editables, should not be changed

I have no idea how to change __FILE__, perhaps using __DIR__."but what is the relative path?"
up
-3
chris at ocproducts dot com
3 years ago
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".
up
-2
dirk at biztechwiz dot com
8 months ago
Getting the magic constants from the right place is important.  For example, creating a function to log location information requires explicit inclusion.

<?php
/***********
* magic_constants_include.php
*
* Magic constant test include file
*/
function showInclude($file=__FILE__, $lineno=__LINE__) {
    echo "Parameter values: $file ($lineno)\n";
    echo "Local constants: " . __FILE__ . "; " . __LINE__ . "\n";
}
?>

<?php
/************
* magic_constants_test.php
*/

require_once 'magic_constants_include.php';

echo "Function call with parameter defaults:\n";
showInclude();

echo "Function call with parameter explicit magic constants:\n";
showInclude(__FILE__, __LINE__);
?>

Results:
php -f magic_constants_test.php
Function call with parameter defaults:
Parameter values: /home/dirk/project/dirk/php/magic_constants_include.php (7)
Local constants: /home/dirk/project/dirk/php/magic_constants_include.php; 9
Function call with parameter explicit magic constants:
Parameter values: /home/dirk/project/dirk/php/magic_constants_test.php (12)
Local constants: /home/dirk/project/dirk/php/magic_constants_include.php; 9
Adding new notes is disabled. Please see the links in the Found A Problem? section.
To Top