【问题标题】:php syntax enclosing bracketsphp 语法用括号括起来
【发布时间】:2015-04-19 13:11:16
【问题描述】:

简单的问题:
一直在探索开源代码,看到如下说法:

$this->{$worker}

用括号括起来是什么意思,this和有什么区别:

$this->worker

【问题讨论】:

标签: php


【解决方案1】:

花括号用于 PHP 中的字符串或变量插值。

类似

$worker = 'foo';
$this->{$worker} = 'bar';

意思是

$this->foo = 'bar';

什么时候有用

class RandomName
{
    protected $foo;
    protected $bar;
    protected $foo_bar;

    $properties_array = array('foo', 'bar', 'foo_bar');
    if (in_array($property, $properties_array)) {
        $this->{$property} = //some value
    }
}

【讨论】:

    【解决方案2】:

    第一个实际使用变量$worker的值,而后者使用表达式/字worker定位对象属性。

    【讨论】:

      【解决方案3】:

      第一个例子是使用一个变量作为属性名。第二个示例是为类的属性使用非变量名称。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-06-26
        • 2022-01-15
        • 2010-09-12
        • 1970-01-01
        • 2021-09-21
        • 2018-02-11
        • 1970-01-01
        相关资源
        最近更新 更多