Предопределенные константы

PHP предоставляет большой список предопределенных констант для каждого выполняемого скрипта. Многие из этих констант определяются различными модулями и будут присутствовать только в том случае, если эти модули доступны в результате динамической загрузки или в результате статической сборки.

Есть пять волшебных констант, которые меняют свое значение в зависимости от контекста, в котором они используются. Например, значение __LINE__ зависит от строки в скрипте, на которой эта константа указана. Специальные константы нечувствительны к регистру и их список приведен ниже:

Таблица 13-1. Некоторые "волшебные" константы PHP

ИмяОписание
__LINE__ Текущая строка в файле.
__FILE__ Полный путь и имя текущего файла.
__FUNCTION__ Имя функции. (Добавлена в PHP 4.3.0.)
__CLASS__ Имя класса. (Добавлена в PHP 4.3.0.)
__METHOD__ Имя метода класса. (Добавлена в PHP 5.0.0)

С полным списком предопределенных констант можно ознакомиться в соответствующем разделе.



Предопределенные константы
warhog at warhog dot net
18-Dec-2005 01:33
There is another magic constant not mentioned above: __COMPILER_HALT_OFFSET__ - contains where the compiler halted - see manual/function.halt-compiler.php for further information.
stalker at NOSPAM dot ruun dot de
17-Dec-2005 01:14
To czabu:
your function can be much more lightweight when you use this:
<?php
function amIincluded() {
 
$requestedURL = parse_url($_SERVER['REQUEST_URI']);
  if(
basename($requestedURL['path']) != basename(__FILE__))
   return
true;
  return
false;
}
?>
vijaykoul_007 at rediffmail dot com
21-Sep-2005 09:59
the difference between
__FUNCTION__ and __METHOD__ as in PHP 5.0.4 is that

__FUNCTION__ returns only the name of the function

while as __METHOD__ returns the name of the class alongwith the name of the function

class trick
{
     function doit()
     {
               echo __FUNCTION__;
     }
     function doitagain()
     {
               echo __METHOD__;
     }
}
$obj=new trick();
$obj->doit();
output will be ----  doit
$obj->doitagain();
output will be ----- trick::doitagain
karl __at__ streetlampsoftware__dot__com
03-Mar-2005 01:39
Note that the magic constants cannot be included in quoted strings.

For instance,
echo "This is the filename: __FILE__";
will return exactly what's typed above.

echo "This is the filename: {__FILE__}";
will also return what's typed above.

The only way to get magic constants to parse in strings is to concatenate them into strings:
echo "This is the filename: ".__FILE__;
csaba at alum dot mit dot edu
03-Mar-2005 04:04
Sometimes you might want to know whether a script is the top level script or whether it has been included.  That could be useful if you want to reuse the routines in another script, but you don't want to separate them out.  Here's a way that seems to be working for me (for both Apache2 module and CLI versions of PHP) on my Win XP Pro system.

By the way, if __FILE__ is within a function call, its value corresponds to the file it was defined in and not the file that it was called from.  Also, I used $script and strtolower instead of realpath because if the script is deleted after inclusion but before realpath is called (which could happen if the test is deferred), then realpath would return empty since it requires an extant file or directory.

Csaba Gabor from Vienna

<?php
if (amIincluded()) return;    // if we're included we only want function defs
function amIincluded() {
//    returns true/false depending on whether the currently
//    executing script is included or not
//    Don't put this function in an include file (duh)!
  
$webP = !!$_SERVER['REQUEST_METHOD'];    // a web request?
  
$script = preg_replace('/\//',DIRECTORY_SEPARATOR,
                          
$_SERVER['SCRIPT_FILENAME']);
   return (
$webP) ? (strtolower(__FILE__)!=strtolower($script)) :
           !
array_key_exists("_REQUEST", $GLOBALS);
}
?>
lm arobase bible point ch
08-Dec-2004 02:17
in reply to x123 at bestof dash inter:
I believe, this is not a bug, but a feature.
__FILE__ returns the name of the include file, while $PHP_SELF returns the relative name of the main file.
It is then easy to get the file name only with substr(strrchr($PHP_SELF,'/'),1)
claude at NOSPAM dot claude dot nl
18-Jul-2004 08:29
Note that __CLASS__ contains the class it is called in; in lowercase. So the code:

class A
{
   function showclass()
   {
       echo __CLASS__;
   }
}

class B extends A
{
}

$a = new A();
$b = new B();

$a->showclass();
$b->showclass();
A::showclass();
B::showclass();

results in "aaaa";
ulrik
04-Mar-2004 07:44
note that __FUNCTION__ define gives the the function name in lowercase
warhog at warhog dot net
06-Feb-2004 12:49
just to read out the filename of the currently proceeded file use
<?php basename(__FILE__); ?>
hixon at colorado dot edu
15-May-2003 05:21
You can use the following in files that you want to include, but not run directly.  The script will exit if it's run as the top-level script, but will not exit if it's included from another script.  Of course this won't work in the command line mode.

if (realpath(__FILE__) == realpath($_SERVER['SCRIPT_FILENAME'])) {
  exit;
}
kop at meme dot com
13-Feb-2003 03:34
The keywords TRUE and FALSE (case insensitive), which represent their respective boolean values, are worth noting here.
darwin[at]buchner[dot]net
14-Mar-2002 04:54
As of version 4.0.6, there is also a handy predefined DIRECTORY_SEPARATOR constant which you can use to make you scripts more portatable between OS's with different directory structures.

<КонстантыВыражения>
 Last updated: Mon, 14 Nov 2005