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.
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()함수를 쓰면 됩니다.
다음은 상수와 변수의 차이점이다:
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블록 안에서는 선언할 수 없습니다.
참고: 클래스 상수.
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.
Constants of constant :
<?php
const foo = hello;
const bar = foo;
const bd = bar;
echo "bd = " .bd; // Prints out: Hello
?>
const ArrayFromTextfile = file("mytextfile.txt", FILE_IGNORE_NEW_LINES);
does not work, it throws an error:
Fatal error: Constant expression contains invalid operations in php shell code on line …
Instead use:
define ("ArrayFromTextfile", file("mytextfile.txt", FILE_IGNORE_NEW_LINES));
print_r(ArrayFromTextfile);
Result:
Array
(
[0] ⇨ Line 1
[1] ⇨ Line 2
[2] ⇨ Line 3
[3] => …
)
With PHP 5.6, multi-dimensional arrays are also possible if you use "const" instead of "define". So,
define('QUARTLIST',array('1. Quarter'=>array('jan','feb','mar'),'2.Quarter'=>array('may','jun','jul')));
won't work with PHP 5.6, but
const QUARTLIST=array('1. Quarter'=>array('jan','feb','mar'),'2.Quarter'=>array('may','jun','jul'));
will.