array ( 0 => 'index.php', 1 => 'PHP Manual', ), 'head' => array ( 0 => 'UTF-8', 1 => 'zh', ), 'this' => array ( 0 => 'function.defined.php', 1 => 'defined', ), 'up' => array ( 0 => 'ref.misc.php', 1 => '杂项 函数', ), 'prev' => array ( 0 => 'function.define.php', 1 => 'define', ), 'next' => array ( 0 => 'function.die.php', 1 => 'die', ), 'alternatives' => array ( ), 'source' => array ( 'lang' => 'zh', 'path' => 'reference/misc/functions/defined.xml', ), ); $setup["toc"] = $TOC; $setup["toc_deprecated"] = $TOC_DEPRECATED; $setup["parents"] = $PARENTS; manual_setup($setup); ?>
(PHP 4, PHP 5, PHP 7, PHP 8)
defined — 检查给定名称的常量是否存在
检查给定 constant_name
的常量是否已定义。
注意:
如果你要检查一个变量是否存在,请使用 isset()。 defined() 函数仅对 常量 有效。如果你要检测某个函数是否存在,使用 function_exists()。
constant_name
常量的名称。
示例 #1 检查常量
<?php
/* 注意引号的使用,这很重要。这个例子是检查
* 如果字符串 'TEST' 是 TEST 常量的名称 */
if (defined('TEST')) {
echo TEST;
}
interface bar {
const test = 'foobar!';
}
class foo {
const test = 'foobar!';
}
var_dump(defined('bar::test')); // bool(true)
var_dump(defined('foo::test')); // bool(true)
?>
示例 #2 检测 Enum Cases(自 PHP 8.1.0 起)
<?php
enum Suit
{
case Hearts;
case Diamonds;
case Clubs;
case Spades;
}
var_dump(defined('Suit::Hearts')); // bool(true)
?>