关键词列表

这些词语在 PHP 中有着特殊的意义。它们中有些像是函数,有些像是常量,但是它们不是真的,它们只是语言结构的一部分。不能使用它们的任何一个作为常量、类名、函数或方法名。但是它们可以被用作类的属性、常量以及类的方法名,或者接口名和 traits 名,除了 class 不能被用作常量名。

PHP 关键词
__halt_compiler() abstract and array() as
break callable case catch class
clone const continue declare default
die() do echo else elseif
empty() enddeclare endfor endforeach endif
endswitch endwhile eval() exit() extends
final finally fn (从 PHP 7.4 开始) for foreach
function global goto if implements
include include_once instanceof insteadof interface
isset() list() match (从 PHP 8.0 开始) namespace new
or print private protected public
require require_once return static switch
throw trait try unset() use
var while xor yield yield from
编译时常量
__CLASS__ __DIR__ __FILE__ __FUNCTION__ __LINE__ __METHOD__
__NAMESPACE__ __TRAIT__

User Contributed Notes

Johnny D. 22-May-2020 06:37
const FORBIDDEN_TYPES = [
    'null',

    'bool',
    'false',
    'true',

    'int',
    'float',

    'string',
];
bla at taxistop dot be 19-Jul-2018 09:50
This list doesn't include 'self' and 'parent', which I take are indeed keywords.
Thomas Hansen 15-Aug-2016 10:08
Please note that reserved words are still not allowed to be used as namespace or as part of it:

<?php
namespace MyNameSpace\List;

class
Test
{
}
?>

This will fail with a Parse error:  syntax error, unexpected 'List' (T_LIST), expecting identifier (T_STRING)
martindilling at gmail dot com 15-Apr-2013 10:20
RegEx to find all the keywords:

\b(
(a(bstract|nd|rray|s))|
(c(a(llable|se|tch)|l(ass|one)|on(st|tinue)))|
(d(e(clare|fault)|ie|o))|
(e(cho|lse(if)?|mpty|nd(declare|for(each)?|if|switch|while)|val|x(it|tends)))|
(f(inal|or(each)?|unction))|
(g(lobal|oto))|
(i(f|mplements|n(clude(_once)?|st(anceof|eadof)|terface)|sset))|
(n(amespace|ew))|
(p(r(i(nt|vate)|otected)|ublic))|
(re(quire(_once)?|turn))|
(s(tatic|witch))|
(t(hrow|r(ait|y)))|
(u(nset|se))|
(__halt_compiler|break|list|(x)?or|var|while)
)\b
Chris 04-Oct-2012 04:33
Here they are as arrays:

<?php
$keywords
= array('__halt_compiler', 'abstract', 'and', 'array', 'as', 'break', 'callable', 'case', 'catch', 'class', 'clone', 'const', 'continue', 'declare', 'default', 'die', 'do', 'echo', 'else', 'elseif', 'empty', 'enddeclare', 'endfor', 'endforeach', 'endif', 'endswitch', 'endwhile', 'eval', 'exit', 'extends', 'final', 'for', 'foreach', 'function', 'global', 'goto', 'if', 'implements', 'include', 'include_once', 'instanceof', 'insteadof', 'interface', 'isset', 'list', 'namespace', 'new', 'or', 'print', 'private', 'protected', 'public', 'require', 'require_once', 'return', 'static', 'switch', 'throw', 'trait', 'try', 'unset', 'use', 'var', 'while', 'xor');

$predefined_constants = array('__CLASS__', '__DIR__', '__FILE__', '__FUNCTION__', '__LINE__', '__METHOD__', '__NAMESPACE__', '__TRAIT__');
?>

Along with get_defined_functions() and get_defined_constants(), this can be useful for checking eval() statements.
PHP8中文手册 站长在线 整理 版权归PHP文档组所有