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';
Question
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';
OTHER TIPS
You object has to implement ArrayAccess interface.
class MyClass extends ArrayAccess
{
private $container = array();
public function offsetSet($offset, $value)
{
if (is_null($offset)) {
$this->container[] = $value;
} else {
$this->container[$offset] = $value;
}
}
public function offsetExists($offset)
{
return isset($this->container[$offset]);
}
public function offsetUnset($offset)
{
unset($this->container[$offset]);
}
public function offsetGet($offset)
{
return isset($this->container[$offset]) ? $this->container[$offset] : null;
}
}