What does $this[$variable] mean in php?

I was reading through 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);
        }
}

and don't understand what $this[$name] means. How can $this be accessed as an array? What exactly is happening here?

I goggled "$this as array" and read the $this documentation again but did not find anything explaining this syntax.

Upvotes: 1

Views: 140

Answers (3)

hyebin
hyebin

Reputation: 1

I came in because I wanted to know about this.

After I saw Havenard's answer and then I tested it, I found out.

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

in class like [Class A implements \ArrayAccess]

$this[$var]; means $this->offsetGet($var);

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

I hope it helped. Thanks Havenard!

Upvotes: 0

Havenard
Havenard

Reputation: 27934

The class SimpleContainer extends Pimple\Container, which implements \ArrayAccess, which enables array-like syntax on your object through a number of methods documented here.

Upvotes: 2

Rando
Rando

Reputation: 473

$this is indicative of a classwide variable. By the looks of the code the class extends container and implements an icontainer, being that it has no constructor in the class you've shown itself, its most likely in the class it extends. There is also a registerParameter class that is likely called before the registerService class

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

Its purpose is to push new values to the variable pulled in the service register

Upvotes: -1

Related Questions