转换数组对象自动array_key_exists() [英] Converting arrays to objects to automate array_key_exists()
问题描述
我需要我的code不抛出任何通知,所以我写了一个小类来访问数组,而不必担心不确定的索引所有的时间。
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?
推荐答案
我想从的 ArrayObject的类是这样的:
class MyArrayObject extends ArrayObject{
public function offsetGet($name) {
if($this->offsetExists($name))
return parent::offsetGet($name);
}
}
与功能 offsetGet()
您可以访问阵列的数据,因此,如果调用 $ myObjectArray ['测试']
函数被调用。然后,如果你用 offsetExists检查()
如果密钥seted您将返回值。否则结果将是空
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
编辑:
如果你也想用这个作为一个对象,你需要添加这两种功能:
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);
}
这篇关于转换数组对象自动array_key_exists()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!