Converting arrays to objects to automate array_key

2019-07-19 17:58发布

问题:

I need my code to not throw any notices, so I've written a little class to access arrays without having to worry about undefined indexes all the time.

class ArrayAsObject
{
  private $array;

  public function __construct(&$array) {
    $this->array = &$array;
  }

  public function __get($key)
  {
    if (array_key_exists($key, $this->array)) {
      return $this->array[$key];
    } else {
      return null;
    }
  }
}

$fruits = array ('apples' => 42);
$fruits = new ArrayAsObject($fruits);

echo $fruits->apples;  // 42
echo $fruits->lemons;  // null

I'm just wondering if this has any unintended consequences, or can I use this for any array and can live happily ever after?

回答1:

I would extend from the ArrayObject class like this:

class MyArrayObject extends ArrayObject{

    public function offsetGet($name) {
        if($this->offsetExists($name))
            return parent::offsetGet($name);
    }
}

with the function offsetGet() you can access your Array data, so if you call $myObjectArray['test'] the function is called. And then if you check with offsetExists() if the key is seted you will return the value. else the result will be null

EDIT:

And if you want to use this also as an object, you need to add these 2 functions:

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

public function __set($name, $value){
    $this->offsetSet($name, $value);
}


回答2:

It should be

$arr = array ('apples' => 42);
$fruits = new ArrayAsObject($arr);

instead of

$fruits = ArrayAsObject(array ('apples' => 42));

What was the mistake ?

You didn't use the new keyword and you directly passed the array (Only variables can be passed by reference) which will result in a notice.



标签: php arrays oop