为什么 PHP 不允许在 CONST 中使用匿名函数? [英] Why PHP doesn't allow anonymous functions inside CONST?

查看:46
本文介绍了为什么 PHP 不允许在 CONST 中使用匿名函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 PHP 中不允许使用此代码?

Why this code isn't allowed in PHP?

const VALIDATOR = array(
    'field' => array(
        'type' => 'string',
        'custom' => function() {
            return true;
    }));

或者这个更简单的版本?

Or even this simpler version?

const MY_FUN = function($param) {
            echo $param;
    };

抛出一个 意外的 T_FUNCTION 错误.

推荐答案

其他答案只复制手册.我将尝试解释函数常量思想的真正问题.

Other answers only copy the manual. I will try to explain the real problem of the function constant idea.

PHP 不能引入函数常量,即使函数的行为可以在编译时确定.这是因为PHP的allow function和const的名字是一样的,也就是说如果PHP允许函数常量,这样的代码

PHP can not introduce function constant even the behavior of a function can be determined in compile time. This is because PHP allow function and const have the SAME name, which means if PHP allowed function constant, such code

function test() {}

const test = function () {};

对于 test() 调用会产生歧义.

will be ambiguous for test() invoke.

常量和函数可以同名很奇怪,在我看来绝对是错误的设计,但它们从第一天起就已经存在了,不能删除,否则会破坏兼容性.

Constant and function can have the same name is very weird, and definitely WRONG design in my opinion, but they already be there from the first day, and can not be removed or will break compatibility.

注意,理论上,引入函数常量可能不会破坏兼容性.PHP 可以添加一个例外规则,不允许同名函数和const,只有当它是一个函数常量时(过去没有函数常量,所以不会破坏兼容性).但这还不够.另一个例外规则是

Note, in theory, introduce function constant may NOT break compatibility. PHP can add an exception rule that do not allow same name function and const only if it is a function constant (there is no function constant in the past, so will not break compatibility). But it's still not enough. Another exception rule is need for

use function A\test;
use const B\test;

如果 B\test 是一个函数常数.

if B\test is a function constant.

但是引擎永远不知道 B\test 是否是函数常量,直到 B\test 的代码被包含/自动加载.以任何方式推迟解析为运行时的命名空间都是不可接受的,因此唯一的可能性是抛出运行时异常.但是我们大多数人都将命名空间视为静态特性,绝不会期待这样的运行时异常.

But the engine never know whether B\test is a function constant, until the code of B\test is included/autoloaded. Postpone namespace resolving to runtime is not acceptable in any ways, so the only possibility is throw runtime exception. But most of us treat namespace as a static feature and will never expect such runtime exception.

所以我认为 PHP 永远不会允许函数常量.

So I think PHP will never allow function constant.

这篇关于为什么 PHP 不允许在 CONST 中使用匿名函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆