【问题标题】:public static final String in PHP [duplicate]PHP中的公共静态最终字符串[重复]
【发布时间】:2015-07-31 08:27:26
【问题描述】:

PHP 中 public static final String str = "Foo"; 的等价物是什么?

我有这样的课:

class MyClass {

    public $TYPE_REGULAR = 'regular';

    public function display($type) {
        if($type===$this->TYPE_REGULAR) {
            return "This is a regular object";
        }
        return "This is not a regular object";
    }
}

在上面的示例中,我不希望 $TYPE_REGULAR 成为成员属性。我希望它类似于 Java 的 public static final String

谢谢。

【问题讨论】:

  • 很确定 const 就是你在这里所追求的......

标签: php


【解决方案1】:

在 PHP 中,您必须使用 const 来表示变量。

您只能将final 用于类和方法。

在你的情况下:

const TYPE_REGULAR = 'regular'; // public is by default

还可以阅读更多关于 PHP 中 static 和 const 的区别: PHP5: const vs static

【讨论】:

  • 我认为应该是TYPE_REGULAR 没有$ 符号。
  • @JakeOpena,谢谢。匆忙错误;)
【解决方案2】:

使用const

...

const TYPE_REGULAR = 'regular';

...

// access it inside the class using
self::TYPE_REGULAR

Documentation

【讨论】:

    猜你喜欢
    • 2016-08-24
    • 1970-01-01
    • 2015-06-04
    • 1970-01-01
    • 1970-01-01
    • 2012-04-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多