PHP \| define() 与 const

新手上路,请多包涵

在 PHP 中,您可以通过两种方式声明常量:

  1. define 关键字
   define('FOO', 1);

  1. 使用 const 关键字
   const FOO = 1;


  • 这两者之间的主要区别是什么?
  • 何时以及为什么要使用其中一种,何时使用另一种?

原文由 danjarvis 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 395
2 个回答

自 PHP 5.3 起,有两种 定义常量 的方法:使用 const 关键字或使用 define() 函数:

 const FOO = 'BAR';
define('FOO', 'BAR');

这两种方式的根本区别在于 const 在编译时定义常量,而 define 在运行时定义它们。这导致了大部分 const 的缺点。 const 的一些缺点是:

  • const 不能用于有条件地定义常量。要定义一个全局常量,它必须在最外层范围内使用:
    if (...) {
       const FOO = 'BAR';    // Invalid
   }
   // but
   if (...) {
       define('FOO', 'BAR'); // Valid
   }

你为什么要这样做呢?一种常见的应用是检查常量是否已经定义:

    if (!defined('FOO')) {
       define('FOO', 'BAR');
   }

  • const accepts a static scalar (number, string or other constant like true , false , null , __FILE__ ),而 define() 采用任何表达式。由于 const 中也允许使用 PHP 5.6 常量表达式:
    const BIT_5 = 1 << 5;    // Valid since PHP 5.6 and invalid previously
   define('BIT_5', 1 << 5); // Always valid

  • const 采用普通常量名称,而 define() 接受任何表达式作为名称。这允许执行以下操作:
    for ($i = 0; $i < 32; ++$i) {
       define('BIT_' . $i, 1 << $i);
   }

  • const s 始终区分大小写,而 define() 允许您通过传递 true 作为第三个参数来定义不区分大小写的常量(注意:定义不区分大小写的常量自 PHP 7.3.0 起已弃用,自 PHP 8.0.0 起已删除):
    define('FOO', 'BAR', true);
   echo FOO; // BAR
   echo foo; // BAR

所以,这是事情不好的一面。现在来看看我个人一直使用 const 的原因,除非出现上述情况之一:

  • const 读起来更好听。它是一种语言构造而不是函数,并且与您在类中定义常量的方式一致。

  • const 是一种语言结构,可以通过自动化工具进行静态分析。

  • const 在当前命名空间中定义一个常量,而 define() 必须传递完整的命名空间名称:

    namespace A\B\C;
   // To define the constant A\B\C\FOO:
   const FOO = 'BAR';
   define('A\B\C\FOO', 'BAR');

  • 由于 PHP 5.6 const 常量也可以是数组,而 define() 还不支持数组。但是,在 PHP 7 中这两种情况都支持数组。
    const FOO = [1, 2, 3];    // Valid in PHP 5.6
   define('FOO', [1, 2, 3]); // Invalid in PHP 5.6 and valid in PHP 7.0

最后,请注意 const 也可以在类或接口中使用来定义 类常量 或接口常量。 define 不能用于此目的:

 class Foo {
    const BAR = 2; // Valid
}
// But
class Baz {
    define('QUX', 2); // Invalid
}

概括

除非您需要任何类型的条件或表达式定义,否则请使用 const s 而不是 define() s - 只是为了便于阅读!

原文由 NikiC 发布,翻译遵循 CC BY-SA 4.0 许可协议

添加 NikiC 的答案。 const 可以通过以下方式在类中使用:

 class Foo {
    const BAR = 1;

    public function myMethod() {
        return self::BAR;
    }
}

你不能用 define() 做到这一点。

原文由 Marcus Lind 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏