【问题标题】:PHP constants - const vs define vs staticPHP 常量 - const vs define vs static
【发布时间】:2014-11-22 07:27:39
【问题描述】:

问题:

  1. const 变量不能被连接(但我们可以通过常量 define 来实现)。
  2. define 在运行时变慢 - 特别是当您有 long 定义列表时。

静态 - 解决方案?

定义,

define('prefix','hello');
define('suffix','world');
define('greeting',prefix.' '.suffix);

静态的,

class greeting 
{
    static public $prefix = 'hello';
    static public $suffix = 'world';
    static public $concat = 'default';

    public function __construct()
    {
        self::$concat = self::$prefix.' '.self::$suffix;
    }
}

问题:

  1. 那么哪一个更快呢?我该如何测试它们?
  2. 为什么我必须先创建greeting 的实例才能更改$concat默认 值(见下文)?

greeting用法:

var_dump(greeting::$concat);  // default

new greeting(); // I don't even need to store it in a variable like $object = new greeting();
var_dump(greeting::$concat); // hello world

这很奇怪。我怎样才能不创建greeting 的实例但仍然可以获得正确的结果?

有什么想法可以让这变得更好吗?

【问题讨论】:

    标签: static constants php-5.5


    【解决方案1】:

    静态属性仍然是可变的!你想要的是类常量:

    <?php
    class greeting
    {
        const prefix = 'hello';
        const suffix = 'world';
    }
    
    echo greeting::prefix, ' ', greeting::suffix ; 
    # Yields: Hello world
    

    如果您有很多常量,您可能希望使用 serialize() 来编写缓存文件并在代码中使用 unserialize()。根据您的用例,文件 open + unserialize() 可能比 PHP 运行器更快。

    【讨论】:

    • 谢谢,我知道,但我需要一些更短的东西。 greeting::saysomething
    • const 只接受标量数据,这与评估表达式的define() 不同。
    猜你喜欢
    • 2011-06-13
    • 2021-02-14
    • 2012-01-07
    • 1970-01-01
    • 1970-01-01
    • 2012-06-24
    • 1970-01-01
    • 2012-08-20
    • 1970-01-01
    相关资源
    最近更新 更多