[PHP]定数

定数の学習メモ

<?php
echo (defined('TEST')) ? "TRUE\n" : "FALSE\n" ;
echo TEST . "\n" ;
echo (defined('TEST')) ? "TRUE\n" : "FALSE\n" ;
define("TEST", "value");
echo (defined('TEST')) ? "TRUE\n" : "FALSE\n" ;
echo TEST . "\n" ;

function define_FOO(){
  define("FOO","bar");
}
define_FOO();
var_dump(get_defined_constants());

echo "//動作するけど…ダメな例\n";
$foo[bar] = "!?\n\n";
echo $foo[bar];

echo "//こういうこと\n";
define("HOGE", "test");
$foo["test"] = "100";
echo $foo[HOGE] . "\n\n" ;

echo undefined;
echo constant("undefined");
?>

結果

FALSE
TEST
FALSE
TRUE
value
array(たくさん) {

  ~途中は略~

  ["TEST"]=>
  string(5) "value"
  ["FOO"]=>
  string(3) "bar"
}
//動作するけど…ダメな例
!?

//こういうこと
100

undefined
Warning: constant(): Couldn't find constant undefined in ファイルパス on line 13

定義されている定数をすべて得るときは

get_defined_constants() を使う。

<?php
$all_constants = get_defined_constants(TRUE);
$error_constants = array();

foreach( $all_constants["internal"] as $k => $v) {
  if( strpos($k, 'E_')===0 ) {
    $error_constants[$k] = $v ;
  }
}
var_dump( $error_constants );
?>

結果

array(13) {
  ["E_ERROR"]=>
  int(1)
  ["E_WARNING"]=>
  int(2)
  ["E_PARSE"]=>
  int(4)
  ["E_NOTICE"]=>
  int(8)
  ["E_STRICT"]=>
  int(2048)
  ["E_CORE_ERROR"]=>
  int(16)
  ["E_CORE_WARNING"]=>
  int(32)
  ["E_COMPILE_ERROR"]=>
  int(64)
  ["E_COMPILE_WARNING"]=>
  int(128)
  ["E_USER_ERROR"]=>
  int(256)
  ["E_USER_WARNING"]=>
  int(512)
  ["E_USER_NOTICE"]=>
  int(1024)
  ["E_ALL"]=>
  int(2047)
}
<?php
foreach(get_defined_constants(true) as $k => $v){
  $first_order[] = $k;
}
var_dump($first_order);

結果

array
  0 => string 'Core' (length=4)
  1 => string 'calendar' (length=8)
  2 => string 'com_dotnet' (length=10)
  3 => string 'date' (length=4)
  4 => string 'filter' (length=6)
  5 => string 'ftp' (length=3)
  6 => string 'hash' (length=4)
  7 => string 'iconv' (length=5)
  8 => string 'json' (length=4)
  9 => string 'odbc' (length=4)
  10 => string 'openssl' (length=7)
  11 => string 'pcre' (length=4)
  12 => string 'standard' (length=8)
  13 => string 'tokenizer' (length=9)
  14 => string 'zlib' (length=4)
  15 => string 'libxml' (length=6)
  16 => string 'dom' (length=3)
  17 => string 'xml' (length=3)
  18 => string 'xsl' (length=3)
  19 => string 'mbstring' (length=8)
  20 => string 'exif' (length=4)
  21 => string 'fileinfo' (length=8)
  22 => string 'gd' (length=2)
  23 => string 'imap' (length=4)
  24 => string 'mcrypt' (length=6)
  25 => string 'mysql' (length=5)
  26 => string 'mysqli' (length=6)
  27 => string 'soap' (length=4)
  28 => string 'sockets' (length=7)
  29 => string 'SQLite' (length=6)
  30 => string 'sqlite3' (length=7)
  31 => string 'ming' (length=4)
  32 => string 'xdebug' (length=6)
Share
関連記事