如何在PHP中的对象变量中执行文本连接?(How to perform text concatenation in object variables in PHP?)

系统教程 行业动态 更新时间:2024-06-14 16:52:52
如何在PHP中的对象变量中执行文本连接?(How to perform text concatenation in object variables in PHP?)

如果我使用“点”在PHP类中的变量中赋值,则失败。

例如:

class bla { public $a = 'a' . 'b'; }

我应该如何处理这个问题呢?

If I use a "dot" to assign a value in a variable in a PHP class, it fails.

For example:

class bla { public $a = 'a' . 'b'; }

How should I approach this otherwise?

最满意答案

您只能在构造函数中执行此操作,因为必须使用常量表达式在声明上初始化类变量/属性。 从手册 :

这个声明可能包括一个初始化,但是这个初始化必须是一个常量值 - 也就是说,它必须能够在编译时进行评估,并且不能依赖运行时信息来进行评估。

这意味着你不能使用任何操作符或函数调用。

class bla { public $a; public function __construct() { $this->a = 'a' . 'b'; } }

You can only do that in the constructor, as class variables/properties must be initialized on declaration with constant expressions. From the manual:

This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

This means you can't use any operators or function calls.

class bla { public $a; public function __construct() { $this->a = 'a' . 'b'; } }

更多推荐

本文发布于:2023-04-05 12:19:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/ecff6afc6917fc60598675c82222b205.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   文本   对象   如何在   object

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!