downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

표현식> <문법
Last updated: Fri, 24 Jul 2009

view this page in

마법 상수

PHP는 어떤스크립트에서도 유효한 많은 수의 미리 정의된 상수를 제공한다. 하지만 이 상수의 대부분은 다양한 확장(extension)에 의해 생성된다. 그래서 그 확장이 같이 컴파일되어 유효하거나 동적인 로딩이 되어있어야 이런 상수가 존재하게 된다.

일곱 가지 마법 상수가 존재한다. 이 상수들은 어디에서 쓰느냐에 따라 용도가 변경된다. 예를 들면, __LINE__상수의 값은 스크립트의 해당 줄과 관련이 있다. 이 특별한 상수들은 대소문자 구별이 없고 다음과 같다:

약간의 "마법" PHP 상수
이름 설명
__LINE__ 파일의 현재 줄 번호
__FILE__ 파일의 전체경로와 파일명. 포함한 파일 안에서 사용하면, 포함된 파일명을 반환합니다.. PHP 4.0.2부터, __FILE__은 언제나 절대 경로를 가지고 있습니다. 이전에는 특정한 경우에서 상대 경로를 가지고 있었습니다.
__DIR__ 파일의 디렉토리. 포함한 파일 안에서는, 포함된 파일의 디렉토리를 반환합니다. 이는 dirname(__FILE__)과 동일합니다. 디렉토리명은 루트 디렉토리가 아닌 이상, 마지막에 슬래시가 없습니다. (PHP 5.3.0에서 추가)
__FUNCTION__ 함수명. (PHP 4.3.0에서 추가) PHP 5부터 이 상수는 정의된 그대로의 함수명을 반환합니다. (대소문자 구분) PHP 4에서는 항상 소문자였습니다.
__CLASS__ 클래스명. (PHP 4.3.0에서 추가) PHP 5부터 이 상수는 정의된 그대로의 클래스명을 반환합니다. (대소문자 구분) PHP 4에서는 항상 소문자였습니다.
__METHOD__ 클래스 메쏘드명 (PHP 5.0.0에서 추가) 메쏘드 명은 정의한 대로 반환됩니다. (대소문자 구분)
__NAMESPACE__ 현재 이름공간 이름 (대소문자 구분). 이 상수는 컴파일 시에 정의됩니다. (PHP 5.3.0에서 추가)

참고: get_class(), get_object_vars(), file_exists(), function_exists().



표현식> <문법
Last updated: Fri, 24 Jul 2009
 
add a note add a note User Contributed Notes
마법 상수
me at jamessocol dot com
26-Jun-2008 01:11
We need an eighth magic constant, something along the lines of __STATIC__. This should return the name of the class from which a static method was called, regardless of where in the inheritance tree the method was defined.

PHP 5.3 has the new use of the static keyword which will help, but it isn't perfect. You still have to repeat yourself frequently.

For example, trying to implement Active Record:

<?php

// In PHP 5.3

class Model
{
    public static function
find()
    {
        echo static::
$class;
    }
}

class
Product extends Model
{
    protected static
$class = __CLASS__;
}

class
User extends Model
{
    protected static
$class = __CLASS__;
}

Product::find(); // "Product"
User::find(); // "User"

?>

<?php

// With __STATIC__ keyword. (Would be better.)

class Model
{
    public static function
find()
    {
        echo
__STATIC__;
    }
}

class
Product extends Model {}

class
User extends Model {}

Product::find(); // "Product"
User::find(); // "User"

?>

[EDITED : Use get_called_class()]
php at kennel17 dot co dot uk
21-Jun-2007 02:29
Further to my previous note, the 'object' element of the array can be used to get the parent object.  So changing the get_class_static() function to the following will make the code behave as expected:

<?php
   
function get_class_static() {
       
$bt = debug_backtrace();
   
        if (isset(
$bt[1]['object']))
            return
get_class($bt[1]['object']);
        else
            return
$bt[1]['class'];
    }
?>

HOWEVER, it still fails when being called statically.  Changing the last two lines of my previous example to

<?php
  foo
::printClassName();
 
bar::printClassName();
?>

...still gives the same problematic result in PHP5, but in this case the 'object' property is not set, so that technique is unavailable.
php at kennel17 dot co dot uk
21-Jun-2007 01:12
In response to stangelanda at gmail dot com, (who suggested a possible fix to get the actual class name of the object, when being called statically).

in PHP5, this fix no longer works. 

Here is some example code:

<?php

 
function get_class_static() {
   
$bt = debug_backtrace();
   
$name = $bt[1]['class'];
    return
$name;
  }

  class
foo {
    function
printClassName() {
      print(
get_class_static() . "<br>");
     }
  }

  class
bar extends foo {
  }

$f = new foo();
$b = new bar();
$f->printClassName();
$b->printClassName();

?>

In PHP4, it outputs
  foo
  bar
as you described.

However, in PHP5, due to the way the debug_backtrace() function has been modified (see http://bugs.php.net/bug.php?id=30828) the output is now
  foo
  foo

I have yet to figure out a way to get the original output in PHP5.  Any suggestions would be very useful, and if I find an answer I'll post it here.
Tomek Perlak [tomekperlak at tlen pl]
10-Nov-2006 07:16
The __CLASS__ magic constant nicely complements the get_class() function.

Sometimes you need to know both:
- name of the inherited class
- name of the class actually executed

Here's an example that shows the possible solution:

<?php

class base_class
{
    function
say_a()
    {
        echo
"'a' - said the " . __CLASS__ . "<br/>";
    }

    function
say_b()
    {
        echo
"'b' - said the " . get_class($this) . "<br/>";
    }

}

class
derived_class extends base_class
{
    function
say_a()
    {
       
parent::say_a();
        echo
"'a' - said the " . __CLASS__ . "<br/>";
    }

    function
say_b()
    {
       
parent::say_b();
        echo
"'b' - said the " . get_class($this) . "<br/>";
    }
}

$obj_b = new derived_class();

$obj_b->say_a();
echo
"<br/>";
$obj_b->say_b();

?>

The output should look roughly like this:

'a' - said the base_class
'a' - said the derived_class

'b' - said the derived_class
'b' - said the derived_class
stangelanda at gmail dot com
06-Sep-2006 01:17
claude noted that __CLASS__ always contains the class that it is called in, if you would rather have the class that called the method use get_class($this) instead.  However this only works with instances, not when called statically.

<?php
 
class A {
     function
showclass() {
         echo
get_class($this);
     }
  }

  class
B extends A {}

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

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

 
//results in "a", "b", false, false
?>

I tried keeping track of the class manually within the properties, but the following doesn't work either:

<?php
 
class A {
     var
$class = __CLASS__;
     function
showclass() {
         echo
$this->class;
     }
  }

  class
B extends A {
     var
$class = __CLASS__;
  }

 
//results in "a", "b", NULL, NULL
?>

The best solution I could come up with was using debug_backtrace.  I assume there is a better way somehow, but I can't find it.  However the following works:

<?php
 
class A {
     function
showclass() {
       
$backtrace = debug_backtrace();
        echo
$backtrace[0]['class'];
     }
  }

  class
B extends A {}

 
//results in "a", "b", "a", "b"
?>
warhog at warhog dot net
19-Dec-2005 06:33
There is another magic constant not mentioned above: __COMPILER_HALT_OFFSET__ - contains where the compiler halted - see http://www.php.net/manual/function.halt-compiler.php for further information.
vijaykoul_007 at rediffmail dot com
22-Sep-2005 01: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
04-Mar-2005 06: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 09: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
09-Dec-2004 07: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
19-Jul-2004 12: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
05-Mar-2004 12:44
note that __FUNCTION__ define gives the the function name in lowercase
warhog at warhog dot net
07-Feb-2004 05:49
just to read out the filename of the currently proceeded file use
<?php basename(__FILE__); ?>
hixon at colorado dot edu
16-May-2003 09: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
14-Feb-2003 08:34
The keywords TRUE and FALSE (case insensitive), which represent their respective boolean values, are worth noting here.
darwin[at]buchner[dot]net
15-Mar-2002 09: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: Fri, 24 Jul 2009
 
 
show source | credits | stats | sitemap | contact | advertising | mirror sites