dsxjot8620 2017-07-24 16:07
浏览 35
已采纳

如何在PHP OOP中仅使用过滤内容创建对象

I have created a class with constructor in php which filter xml file. But the object created take all xml data. How can I avoid that?

Thank you for your help!

My code:

class  Property {
    public $xmlClass;
    public $elemClass = '';
    public $result_array = [];
    public $data = '';

    public function __construct($xml,$elem) {
        $this->xmlClass=$xml;
        $this->elemClass=$elem;

        foreach($xml->list->movie as $value) {
            $data = $value->$elem;
            $result_array[] = $data;
        }

        print_r($result_array);                   //here everything is ok
    }
}

$result_title = new Property('title');
print_r($result_title);    //here object takes all data, not only filtered
  • 写回答

2条回答 默认 最新

  • dongtanxi5676756 2017-07-24 16:20
    关注

    $result_title is an object with a lot of props. Among them there's your initial xml as you assign it to xmlClass property.

    To get the desired data you need to store it in a class property, you already declare it ($result_array).

    So, a proper code could be:

    class  Property {
        public $xmlClass;
        public $elemClass = '';
        public $result_array = [];
        public $data = '';
    
        public function __construct($xml,$elem) {
            $this->xmlClass=$xml;
            $this->elemClass=$elem;
    
            foreach($xml->list->movie as $value) {
                $data = $value->$elem;
                // add data to a class property `result_array`
                $this->result_array[] = $data;
            }
        }
    
        // get value of `result_array` with this method
        public function getResultArray() 
        {
            return $this->result_array;
        }
    }
    
    $result_title = new Property('title');
    print_r($result_title->getResultArray());
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退
  • ¥20 win系统的PYQT程序生成的数据如何放入云服务器阿里云window版?