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
}
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
}
Just add implements ArrayAccess
to your class and add the required methods:
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 :
ArrayAccess::offsetExists
: Whether or not an offset exists. ArrayAccess::offsetGet
: Returns the value at specified offset.ArrayAccess::offsetSet
: Assigns a value to the specified offset. ArrayAccess::offsetUnset
: Unsets an offset. There is a full example on the manual's page I pointed to ;-)
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.
Your object must implement the ArrayAccess
interface, then PHP will allow you to use the square brackets like that.
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'];
You could also cast the object as an array:
if((array)$obj['foo'] == 'bar'){
//more code here
}