dspld86684 2014-10-24 15:22
浏览 43
已采纳

get_object_vars()可以从magic __get()返回字段吗?

I'm running through a set of arrays and objects for further processing. If it's an object i use get_object_vars($obj) to get its proberties. But if that object uses magic getters/setters, it returns an empty array. Here a little demo of the issue:

class Foo {
    protected
        $fields = array(
            'foo'=>1,
            'bar'=>2
        );
    function __get($key) {
        return $this->fields[$key];
    }
    function __isset($key) {
        return array_key_exists($key,$this->fields);
    }
}

$foo = new Foo();
var_dump(get_object_vars($foo));

I want that get_object_vars returns the $fields key-value pairs. Is there any way to go, or any method to implement in Foo to make it work?

thanks for any hint.

  • 写回答

2条回答 默认 最新

  • duanhe1965 2014-10-24 16:45
    关注

    That is not related to magic methods, but with the fact that get_object_vars() returns an array of accessible non-static properties for the specified object relative to scope. It will return all properties if the call is from inside the objects, but, only public from outside the object. You can however, use the IteratorAggregate interface, and ArrayIterator class, and combine that with iterator_to_array() function to obtain similar behavior and some additional benefits, as in this example.

    class Foo implements IteratorAggregate {
        protected
            $fields = array(
                'foo' => 1,
                'bar' => 2
            );
    
        function __get( $name ) {
            return array_key_exists( $name, $this->fields ) ? $this->fields[$name] : null;
        }
    
        public function __set( $name, $value )
        {
            $this->fields[$name] = $value;
        }
    
        function __isset( $name ) {
            return isset( $this->fields[$name] );
        }
    
        public function getIterator() {
            return new ArrayIterator( $this->fields );
        }
    }
    
    $foo = new Foo();
    $foo->baz = 3;
    
    foreach( $foo as $key => $value ) {
        echo "$key: $value ";   // OUTPUT: foo: 1 bar: 2 baz: 3
    }
    
    array_walk( ( iterator_to_array( $foo ) ), function( $value, $key ) {
        echo "$key: $value ";   // OUTPUT: foo: 1 bar: 2 baz: 3
    });
    
    print_r( iterator_to_array( $foo ) );   // OUTPUT: Array ( [foo] => 1 [bar] => 2 [baz] => 3 ) 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法