1

I know using ArrayAccess interface we can use object as array(getting setting unseting).And i have idea that ArrayAcess interface contain 4 undefined methods.we should implement these methods if class implements arrrayacess. i removed "implements arrayaccess" from Varien_Object class.but still i'm not getting any error. so my question is where Varien_Object reference used as array?. please give me some examples.and why i'm not getting any error? thanks in advance.

1 Answer 1

1

Varien_Object implements the ArrayAccess interface so you can use instances of it's class like arrays.

Here is a small example.

$obj = new Varien_Object(array(1, 2, 4));
echo $obj[2];

The code above prints out '4'.
Now if you remove implements ArrayAccess the same code will get you

Fatal error: Cannot use object of type Varien_Object as array in ...FILE NAME HERE

Here is an other example:

$obj = new Varien_Object(array('a'=>'aa','b'=>'bb'));
echo $obj['a'];

The code above prints aa.

$obj = new Varien_Object(array('a'=>'aa','b'=>'bb'));
echo $obj[1];

The code above prints ...nothing because the result is null.

In these 2 other cases you get an error if you remove the implements ArrayAccess.

Fatal error: Cannot use object of type Varien_Object as array in ...FILE NAME HERE

You don't get an error because maybe you didn't use the instances of Varien_Object like I did in the examples above.

2
  • So can i say magento never used Varien_Object class reference as Array?. So why Magento team using ArrayAccess Interface for Varien_Object class?I think child classes references uses as array.I hope you can give some examples.
    – sivakumar
    May 22, 2014 at 11:28
  • @sivakumar. Let's say you have a product instance and you want to get the name. The nice way of doing it is $product->getName(). But I've seen some extensions that use something like this $product['name']. If Varien_Object implemente ArrayAccess this works just fine. I honestly don't like it, and don't encourage it, but it works. Could be useful if you write some function that can receive as parameter either an object or an array. This way you don't need to check what type the parameter is.
    – Marius
    May 22, 2014 at 11:34

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.