PHP implements ArrayAccess

I have two classes: foo and Bar

class bar extends foo
{

    public $element = null;

    public function __construct()
    {
    }
}

and the class foo is like

class foo implements ArrayAccess
{

    private $data = [];
    private $elementId = null;

    public function __call($functionName, $arguments)
    {
        if ($this->elementId !== null) {
            echo "Function $functionName called with arguments " . print_r($arguments, true);
        }
        return true;
    }

    public function __construct($id = null)
    {
        $this->elementId = $id;
    }

    public function offsetSet($offset, $value)
    {
        if (is_null($offset)) {
            $this->data[] = $value;
        } else {
            $this->data[$offset] = $value;
        }
    }

    public function offsetExists($offset)
    {
        return isset($this->data[$offset]);
    }

    public function offsetUnset($offset)
    {
        if ($this->offsetExists($offset)) {
            unset($this->data[$offset]);
        }
    }

    public function offsetGet($offset)
    {
        if (!$this->offsetExists($offset)) {
            $this->$offset = new foo($offset);
        }
    }
} 

I want when I run the following code snippet:

$a = new bar();
$a['saysomething']->sayHello('Hello Said!');

should return Function sayHello Called with arguments Hello Said! from the magic method foo __call.

Here I want to say that sayomething should be passed to $ this-> elementId from the foo __ construct function and sayHello should be used as a method, and Hello Said should be used as parameters of the sayHello function that will be displayed from the __ call magic method .

In addition, you must associate methods such as:

$a['saysomething']->sayHello('Hello Said!')->sayBye('Good Bye!');
+3
source
1

, foo::offsetGet() :

public function offsetGet($offset)
{
    if (!$this->offsetExists($offset)) {
        return new self($this->elementId);
    } else {
        return $this->data[$offset];
    }
}

, .

, foo::__construct() bar::__construct() , null:

class bar extends foo
{

    public $element = null;

    public function __construct()
    {
        parent::__construct(42);
    }
}

, __call():

public function __call($functionName, $arguments)
{
    if ($this->elementId !== null) {
        echo "Function $functionName called with arguments " . print_r($arguments, true);
    }
    return $this;
}
+2

All Articles