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

查看:19
本文介绍了我可以使用字符串连接在 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?

推荐答案

恕我直言,这个问题值得 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
"; 
}

虽然这不是问题的一部分,但应该意识到实施的局限性.以下内容不起作用,尽管它是静态内容(但可能在运行时被操纵):

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
"; 
}
// 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
"; 
}
// PHP Parse error:  syntax error, unexpected '(', expecting ',' or ';'

有关更多信息,请查看:https://wiki.php.net/rfc/const_scalar_exprshttp://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天全站免登陆