我可以使用字符串连接在PHP中定义一个类CONST吗? [英] Can I use string concatenation to define a class CONST in PHP?

查看:229
本文介绍了我可以使用字符串连接在PHP中定义一个类CONST吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道你可以使用字符串连接创建全局常量:

I know that you can create global constants in terms of each other using string concatenation:

define('FOO', 'foo');
define('BAR', FOO.'bar');  
echo BAR;

将打印'foobar'。

will print 'foobar'.

但是,我尝试使用类常量做同样的错误。

However, I'm getting an error trying to do the same using class constants.

class foobar {
  const foo = 'foo';
  const foo2 = self::foo;
  const bar = self::foo.'bar';
}

foo2定义没有问题,但声明const bar会出错

foo2 is defined without issue, but declaring const bar will error out


解析错误:语法错误,意外的'。',期望','或';'

Parse error: syntax error, unexpected '.', expecting ',' or ';'

我也尝试过使用像sprintf()这样的函数,但它不像左括号任何超过字符串连接器'。'。

I've also tried using functions like sprintf() but it doesn't like the left paren any more than the string concatenator '.'.

因此,有什么方法可以创建类常量,而不是像foo2这样的简单集合。

So is there any way to create class constants in terms of each other in anything more than a trivial set case like foo2?

推荐答案

Imho,此问题值得为 PHP 5.6 + 提供解答,感谢@jammin

Imho, this question deserves an answer for PHP 5.6+, thanks to @jammin comment

从PHP 5.6开始,您可以使用自定义属性为常量定义静态标量表达式:

Since PHP 5.6 you are allowed to define a static scalar expressions for a constant:

class Foo { 
  const BAR = "baz";
  const HAZ = self::BAR . " boo\n"; 
}

虽然这不是问题的一部分,的实现。以下内容不会工作,虽然它是静态内容(但可能在运行时被操作):

Although it is not part of the question, one should be aware of the limits of the implementation. The following won't work, although it is static content (but might be manipulated at runtime):

class Foo { 
  public static $bar = "baz";
  const HAZ = self::$bar . " boo\n"; 
}
// PHP Parse error:  syntax error, unexpected '$bar' (T_VARIABLE), expecting identifier (T_STRING) or class (T_CLASS)

class Foo { 
  public static function bar () { return "baz";}
  const HAZ = self::bar() . " boo\n"; 
}
// PHP Parse error:  syntax error, unexpected '(', expecting ',' or ';'

有关详细信息,请参阅: https://wiki.php .net / rfc / const_scalar_exprs http://php.net/ manual / en / language.oop5.constants.php

For further information take a look at: https://wiki.php.net/rfc/const_scalar_exprs and http://php.net/manual/en/language.oop5.constants.php

这篇关于我可以使用字符串连接在PHP中定义一个类CONST吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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