2

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?

3
  • 2
    why not use $o->param = 'xxx' ? Commented Mar 21, 2014 at 13:42
  • Question isn't in it. I want to know can I do it like in my example Commented Mar 21, 2014 at 13:44
  • @MarcB Read the answers and you'll know how to do your "apple taste like an orange" :) Commented Mar 21, 2014 at 14:04

2 Answers 2

5

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';
Sign up to request clarification or add additional context in comments.

3 Comments

Is ArrayAccess is a standart PHP interface?
@Victor Have you read the doc that both answered posted? It says it right there on the top of the page.
@AzizSaleh It was a simple question :)
4

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;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.