CakeFest 2024: The Official CakePHP Conference

マジック定数

使われる場所によって値が変化する定数(マジック定数)が 9 つあります。 例えば、__LINE__はスクリプト上において 使われる行によって値が変化します。 これらの "マジック"定数は、実行時に解決される通常の定数とは異なり、コンパイル時に解決されます。 これらの特別な定数は大文字小文字を区別しません。 内容は以下のとおりです:

PHP の "マジック" 定数
名前 説明
__LINE__ ファイル上の現在の行番号。
__FILE__ ファイルのフルパスとファイル名 (シンボリックリンクを解決した後のもの)。 インクルードされるファイルの中で使用された場合、インクルードされるファイルの名前が返されます。
__DIR__ そのファイルの存在するディレクトリ。include の中で使用すると、 インクルードされるファイルの存在するディレクトリを返します。 つまり、これは dirname(__FILE__) と同じ意味です。 ルートディレクトリである場合を除き、ディレクトリ名の末尾にスラッシュはつきません。
__FUNCTION__ 関数名。無名関数の場合は、{closure}
__CLASS__ クラス名。 クラス名には、そのクラスが宣言されている名前空間も含みます (例 Foo\Bar)。 トレイトのメソッド内で __CLASS__ を使うと、 そのトレイトを use しているクラスの名前を返します。
__TRAIT__ トレイト名。 トレイト名には、宣言された名前空間も含みます (例 Foo\Bar)。
__METHOD__ クラスのメソッド名。
__NAMESPACE__ 現在の名前空間の名前。
ClassName::class 完全に修飾されたクラス名。

add a note

User Contributed Notes 3 notes

up
2
Rich
8 months ago
<?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.
up
1
chris at ocproducts dot com
10 months 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
0
theking2 at king dot ma
1 year 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.
To Top