PHP Velho Oeste 2024

문법

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

PHP 5.6 이전에는 스칼라 데이터(boolean, integer, float and string)만 상수로 등록할 수 있습니다. 5.6 이후에는 스칼라 표현식을 상수로 정의할 수 있고, array 또한 등록할 수 있습니다. 또, resource를 상수로 정의할 수는 있지만 예상치 못한 문제를 야기할 수 있으므로 사용하지 않을 것을 권고합니다.

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

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

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

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

  • 상수는 이름 앞에 달러표시($)가 없다.
  • PHP 5.3 이전에는,단순한 할당 연산이 아니라 define() 함수로만 정의될수 있다.
  • 상수는 변수의 유효범위 규칙과는 상관없이 어느곳에서든 정의되거나 값을 취할수 있다.
  • 상수는 한번 설정되면 재정의하거나 해제할수 없을것이다; 그리고
  • PHP 5.6 이후에서는, 상수는 스칼라 값 혹은 array의 값으로만 평가됩니다. 상수 스칼라 표현식에 array를 쓸 수 있습니다. (예를들어, const FOO = array(1,2,3)[0];) 하지만 최종 결과는 스칼라 값이어야 합니다.

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;

// PHP 5.6.0 부터 작동
const ANOTHER_CONST CONSTANT.'; Goodbye World';

echo 
ANOTHER_CONST;
?>

Note:

define()을 통하여 정의하는 상수와 달리, const 키워드를 통하여 정의하는 상수는 컴파일 시에 정의되기에 최상위 영역에서 선언해야 합니다. 함수, 루프, if구문이나 try/ catch블록 안에서는 선언할 수 없습니다.

참고: 클래스 상수.

add a note add a note

User Contributed Notes 2 notes

up
31
souzanicolas87 at gmail dot com
2 years ago
the documentation doesn't go too far in explaining the crucial difference between the two ways of declaring constants in PHP.

Const is handled at compile time, define() at run time. For this reason, a constant cannot be conditionally defined using Const, for example.

Another difference we can notice occurs in the constant declarations in classes. Const infiltrates the class scope, while define() leaks into the global scope.

<?php

Class Myclass (){
    const
NAME = "Nicolas";
}

?>

The NAME constant is within the scope of the MyClass class.
up
8
login at (two)view dot de
6 years ago
Just a quick note:
From PHP7 on you can even define a multidimensional Array as Constant:

define('QUARTLIST',array('1. Quarter'=>array('jan','feb','mar'),'2.Quarter'=>array('may','jun','jul'));

does work as expected.
To Top