php - Converting arrays to objects to automate array_key_exists() -


I do not want to send any notice to my code, so I have to use the array without worrying A little class is written for undefined indexes all the time.

  class ArrayAsObject {Private $ array; Public function __ composition (& amp; $ array) {$ this- & gt; Array = & amp; $ Array; } Public function __get ($ key) {if (array_key_exists ($ key, $ this-> array)) {return $ this-> array [$ key]; } And {return tap; }}} $ Fruit = array ('apple' => 42); $ Fruits = new Array object ($ fruit); Echo $ fruit-> Apple; // 42 resonance $ fruit-> Lemon; // null   

I'm just wondering if this is an unexpected result, or can I use it for any array and live happily later?

I will expand from class like this:

  class MyArrayObject ArrayObject Extended {public function offsetGet ($ name) {if ($ this-> OffsetExists ($ name)) Returns parent :: offsetgate ($ name); }}   

You can access your array data from offsetGet () , so if you select $ myObjectArray ['test'] function is called and then if you check with offsetExists () , if the key is set then you will return the value. Otherwise the result will be zero.

Edit:

And if you want to use it as an object too, then you should get these 2 functions Must add:

  public function __get ($ name) {return $ this- & gt; Offsetgate ($ name); } Public function __set ($ name, $ value) {$ this- & gt; Offsetset ($ name, $ value); }    

Comments

Popular posts from this blog

Pass DB Connection parameters to a Kettle a.k.a PDI table Input step dynamically from Excel -

multithreading - PhantomJS-Node in a for Loop -

c++ - MATLAB .m file to .mex file using Matlab Compiler -