代码之家  ›  专栏  ›  技术社区  ›  Zacky112

在对象上使用数组函数

php
  •  1
  • Zacky112  · 技术社区  · 15 年前

    array_values() array_key_exists() 用在物体上?

    4 回复  |  直到 15 年前
        1
  •  5
  •   Eric Petroelje    15 年前

    array_key_exists() 用于对象,但从PHP5.3.0开始,就不再适用了。你应该使用 property_exists() 相反。

        2
  •  2
  •   Shabbyrobe    15 年前

    PHP对象可以被强制转换为一个数组,而不需要方法调用,而且几乎没有性能损失,这将允许您在属性上使用任何您喜欢的数组函数。

    $arr = (array) $obj;
    

    在PHP中使用语言构造几乎总是比调用方法快得多。 isset 被认为是一种语言结构。

    我意识到这有一点过早优化的味道,但是在php5.3中运行以下代码的结果可能会让您感到惊讶。

    <?php
    $count = 50000;
    
    class Pants
    {
        public $mega='wad';
        public $pung=null;
    }
    
    $s = microtime(true);
    for ($i=0; $i < $count; $i++) {
        $p = new Pants;
        $e = property_exists($p, 'mega');
        $e = property_exists($p, 'pung');
    }
    var_dump(microtime(true) - $s);
    
    $s = microtime(true);
    for ($i=0; $i < $count; $i++) {
        $p = new Pants;
        $p = get_object_vars($p);
        $e = isset($p['mega']);
        $e = isset($p['pung']);
    }
    var_dump(microtime(true) - $s);
    
    $s = microtime(true);
    for ($i=0; $i < $count; $i++) {
        $p = new Pants;
        $p = (array) $p;
        $e = isset($p['mega']);
        $e = isset($p['pung']);
    }
    var_dump(microtime(true) - $s);
    

    输出:

    float(0.27921605110168)
    float(0.22439503669739)
    float(0.092200994491577)
    

        3
  •  0
  •   yclian    15 年前

    对于 array_values() ,使用 get_object_vars() 获取其公共属性(如果要获取受保护的属性和私有属性,则取决于客户端代码的范围)。

    如果你想要更多的东西, ReflectionObject

        4
  •  0
  •   jmz    15 年前

    如果您确实需要 array_values array_keys ,您可以这样做: $keys = array_keys(get_object_vars($obj)) $values = array_values(get_object_vars($obj))

    keys values . 然后在类中实现这些方法以获取键和值。其他类似数组的接口在 ArrayIterator 班级。

    推荐文章