Search code examples
phpoopmagic-methods

How can I use object as an array?


I want to use next syntax:

$o = new MyClass();
$o['param'] = 'value'; // set property "param" in "value" for example

Now I have an error:

Fatal error: Cannot use object of type MyClass as array

Can I use object like this? Maybe there are any magic methods?


Solution

  • What you could do, is create a new class called MyClass and make it implement the ArrayAccess interface.

    You can then use:

    $myArray = new MyClass();
    $myArray['foo'] = 'bar';
    

    Although it's easier to just use:

    $myArray->foo = 'bar';