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

문법

define() 함수를 사용해서 상수를 정의할 수 있습니다. PHP 5.3.0부터 클래스 정의 밖에서 const 키워드를 사용할 수도 있습니다. 상수가 한번 정의되면, 변경하거나 해제(undefine)할 수 없습니다.

상수는 스칼라 데이터(boolean, integer, float, string)만 가질 수 있습니다. resource를 상수로 등록할 수 있지만, 피하십시오. 예상할 수 없는 결과를 낳을 수 있습니다.

단순히 상수명을 써서 상수값을 얻을 수 있다. 변수와는 달리 $가 상수명 앞으로 오면 안된다 동적으로 상수명을 취하려한다면 constant()함수로 상수값을 가져올수 있다. 정의된 모든 상수 목록을 구하려면 get_defined_constants() 함수를 쓴다.

Note: 상수와 (전역)변수는 서로 다른 네임스페이스(namespace)상에 있다. 이말의 의미는 예를 들면 TRUE$TRUE은 일반적으로 다르다는것이다.

해제된 상수를 사용한다면, PHP는 상수명 자체를 쓴것이라고 가정할것이다 즉,string으로 인식할것이다. (CONSTANT vs "CONSTANT") E_NOTICE로 이런 일이 발생했는지 알수 있다. 왜 $foo[bar]가 잘못됐는지 (bar를 상수로 define() 하지않았다면) 매뉴얼을 참고한다. 단순히 상수가 설정되었는지만 확인하려 한다면 defined()함수를 쓰면 됩니다.

다음은 상수와 변수의 차이점이다:

  • 상수는 이름 앞에 달러표시($)가 없다.
  • 상수는 단순 지정(assingment)이 아니라 define() 함수로만 정의될수 있다.
  • 상수는 변수의 유효범위 규칙과는 상관없이 어느곳에서든 정의되거나 값을 취할수 있다.
  • 상수는 한번 설정되면 재정의하거나 해제할수 없을것이다; 그리고
  • 상수는 스칼라 값만 쓸수 있다.

Example #1 상수 정의하기

<?php
define
("CONSTANT""Hello world.");
echo 
CONSTANT// "Hello world."을 출력한다
echo Constant// "Constant"를 출력하고 경고가 뜬다.
?>

Example #2 const 키워드를 사용해서 상수 정의하기

<?php
// PHP 5.3.0부터 작동
const CONSTANT 'Hello World';

echo 
CONSTANT;
?>

참고: 클래스 상수.



add a note add a note User Contributed Notes
문법
uramihsayibok, gmail, com
09-Aug-2009 03:54
Don't let the comparison between const (in the global context) and define() confuse you: while define() allows expressions as the value, const does not. In that sense it behaves exactly as const (in class context) does.

<?php

// this works
/**
 * Path to the root of the application
 */
define("PATH_ROOT", dirname(__FILE__));

// this does not
/**
 * Path to configuration files
 */
const PATH_CONFIG = PATH_ROOT . "/config";

// this does
/**
 * Path to configuration files - DEPRECATED, use PATH_CONFIG
 */
const PATH_CONF = PATH_CONFIG;

?>

마법 상수> <상수
Last updated: Fri, 24 Jul 2009
 
 
show source | credits | stats | sitemap | contact | advertising | mirror sites