tags:

views:

219

answers:

7

I need to be able to set my object like this:

$obj->foo = 'bar';

then after that is set i need the following to be true

if($obj['foo'] == 'bar'){
  //more code here
}
+6  A: 

Try extending ArrayObject

valya
I have this class Obj extends ArrayObject{} But when i am doing my unit testing i get a failure on the above.
oxfletchox
yes, now you need to define there function __get() and __set(). For example, function __get($n) { return $this[$n]; }
valya
Thank you very much, i was missing the helper function.
oxfletchox
+5  A: 

Just add implements ArrayAccess to your class and add the required methods:

  • public function offsetExists($offset)
  • public function offsetGet($offset)
  • public function offsetSet($offset, $value)
  • public function offsetUnset($offset)

See http://php.net/manual/en/class.arrayaccess.php

Gordon
+5  A: 

You'll have to implement the ArrayAccess interface to be able to do that -- which only means implementing a few (4 to be exact) simple methods :

There is a full example on the manual's page I pointed to ;-)

Pascal MARTIN
@Gordon : ergh, thanks ! I generally copy-paste the names of classes/methods to avoid that kind of mistake... This time I thought "I can type this"... Well, it seems not ^^
Pascal MARTIN
+7  A: 

You're mixing objects and arrays. You can create and access an array like so:

$obj = new stdClass;
$obj->foo = 'bar';

if($obj->foo == 'bar'){
// true
}

and an array like so:

$obj = new Array();
$obj['foo'] = 'bar';

if($obj['foo'] == 'bar'){
// true
}

You can define a class and add implements ArrayAccess if you want to access your class as both an array and a class.

http://www.php.net/manual/en/language.oop5.php

adam
+3  A: 

Your object must implement the ArrayAccess interface, then PHP will allow you to use the square brackets like that.

soulmerge
+2  A: 

ArrayObject implements the ArrayAccess interface (and some more). Using the ARRAY_AS_PROPS flag it provides the functionality you're looking for.

$obj = new ArrayObject(array(), ArrayObject::ARRAY_AS_PROPS);
$obj->foo = 'bar';
echo $obj['foo'];

Alternatively you can implement the ArrayAccess interface in one of your own classes:

class Foo implements ArrayAccess {
  public function offsetExists($offset) {
    return isset($this->$offset);
  }

  public function offsetGet($offset) {
    return $this->$offset;
  }

  public function offsetSet($offset , $value) {
    $this->$offset = $value;
  }

  public function offsetUnset($offset) {
    unset($this->$offset);
  }
}

$obj = new Foo;
$obj->foo = 'bar';
echo $obj['foo'];
VolkerK
A: 

You could also cast the object as an array:

if((array)$obj['foo'] == 'bar'){
  //more code here
}
ceejayoz