[英]PHP OOP: Can the value of an object property be a function?
My question is quite simple: In PHP OOP I want the value of an object property to be returned by a function . 我的问题很简单:在PHP OOP中,我希望对象的值由函数返回 。 To be specific: I want a string to be translated with gettext.
具体来说:我希望使用gettext转换字符串。 But it seems, that the value of a property has to be a string, a number or an array but not a function.
但是似乎属性的值必须是字符串,数字或数组,而不是函数。
My code is similar to this: 我的代码与此类似:
<?php
class Bar extends Foo {
public $baz = array('lorem' => __('ipsum'));
// other code
?>
If you look at the manual regarding properties
, you will see that: 如果您查看有关
properties
的手册,则会看到:
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.
该声明可以包括一个初始化,但是此初始化必须是一个常量值-也就是说,它必须能够在编译时进行评估,并且必须不依赖于运行时信息才能进行评估。
So you cannot use a function when you declare the property. 因此,在声明属性时不能使用函数。
However, the value can be set somewhere else, so in your case you could set it for example in the constructor: 但是,可以在其他位置设置该值,因此在您的情况下,可以在构造函数中进行设置:
<?php
class Bar extends Foo {
public $baz;
function __construct()
{
$this->baz = array('lorem' => __('ipsum'));
}
// other code
?>
Properties in PHP for classes must be a scalar value, therefore, you cannot expect to call a function as the property value. PHP中类的属性必须是标量值,因此,不能期望将函数作为属性值调用。 To properly to do this, you would need to set the value in the constructor.
为了正确地做到这一点,您需要在构造函数中设置值。
<?php
class Bar extends Foo {
public $baz = array('lorem' => NULL);
public function __construct()
{
$this->baz['lorem'] = __('ipsum')
}
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.