Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 767
Victor Bocharsky Avatar asked Aug 22 '26 17:08

Victor Bocharsky


1 Answers

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';
like image 148
Pim Verlangen Avatar answered Aug 25 '26 06:08

Pim Verlangen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!