这个[$ variable]在php中意味着什么?

时间:2018-04-26 00:34:54

标签: php this

我正在阅读this code

public function registerService($name, Closure $closure, $shared = true) {
        $name = $this->sanitizeName($name);
        if (isset($this[$name]))  {
            unset($this[$name]);
        }
        if ($shared) {
            $this[$name] = $closure;
        } else {
            $this[$name] = parent::factory($closure);
        }
}

并且不明白$this[$name]的含义。如何将$作为数组访问?到底发生了什么?

我将“$ this as array”goggled并再次阅读$this documentation,但没有找到解释此语法的内容。

3 个答案:

答案 0 :(得分:1)

SimpleContainer扩展Pimple\Container,它实现\ArrayAccess,通过多种方法documented here为您的对象启用类似数组的语法。

答案 1 :(得分:0)

我进来是因为我想知道这一点。

当我看到Havenard的答案并进行测试后,我发现了。

class A implements \ArrayAccess
{
    private $array;
    public function __construct()
    {
        $this->array = array("one"=>1, "two"=>2, "three"=>3);
    }
    public function WhatDoesThisArray($val1)
    {
        $this[$val1] = 99;
        $this[$val1];
        var_dump($this[$val1]);
        echo $this[$val1];
    }
    public function offsetExists($offset)
    {
        echo "call offsetExists\n";
    }
    public function offsetGet($offset)
    {
        echo "call offsetGet($offset)\n";
        return $this->array[$offset];
    }
    public function offsetUnset($offset)
    {
        echo "call offsetUnset\n";
    }
    public function offsetSet($offset, $value)
    {
        echo "call offsetSet\n";
        $this->array[$offset] = $value;
    }
}

/* Test */
$testClass = new A();
$testClass->WhatDoesThisArray("two");

/* Result */
call offsetSet
call offsetGet(two)
call offsetGet(two)
int(99)
call offsetGet(two)
99

在类似[A类实现\ ArrayAccess]

的类中

$ this [$ var]; 意味着 $ this-> offsetGet($ var);

$ this [$ var] = $ value; 表示 $ this-> offsetSet($ var,$ value);

我希望能有所帮助。谢谢Havenard!

答案 2 :(得分:-1)

$这表示一个全班变量。通过代码的外观,类扩展容器并实现一个icontainer,因为它在你自己展示的类中没有构造函数,它最有可能在它扩展的类中。还有一个registerParameter类可能在registerService类

之前调用
public function registerParameter($name, $value) {
    $this[$name] = $value;
}

其目的是将新值推送到服务寄存器中拉出的变量

相关问题