【问题标题】:Calling Method of array of objects?对象数组的调用方法?
【发布时间】:2012-05-20 22:58:46
【问题描述】:

如何从对象数组(包含对象数组)中调用方法。我读到:Get array with results of object method on each item in an array of objects in PHP,但没读懂。

这是我的测试代码:第一个对象保存属性,然后一个对象保存多个属性的记录。

/*--------------------------------- */
class SqliteAttribute {

    private $_fieldname = '';
    private $_fieldvalue = '';
    private $_type = 'TEXT';
    private $_key = true;

    function __construct($fieldname, $fieldvalue, $text, $key) {
        $this->_fieldname  = $fieldname;
        $this->_fieldvalue = $fieldvalue;
        $this->_text       = $text;
        $this->_key        = $key;
    }

    function AsArray() {
        $tempArray = array('fieldname'     => $this->_fieldname,
                           'fieldvalue'    => $this->_fieldvalue,
                           'type'          => $this->_type,
                           'key'           => $this->_key
        );
        return $tempArray;
    }
}

/*--------------------------------- */
class SqliteRecord {

    private $_attributes = array();

    function __construct() {
    }

    function AddAttribute($fieldname, $fieldvalue, $text, $key) {
        $attribute          = new SqliteAttribute($fieldname, $fieldvalue, $text, $key);
        $this->attributes[] = $attribute;
        var_dump($this->_attributes); // shows it!
    }

    function AsArray() {
        $temp_array = array();
        var_dump($this->_attributes); // shows nothing
        foreach ($this->_attributes as $key => $value) {
            $temp_array[] = $value->AsArray();
        }
        return $temp_array;
    }

}

我这样称呼它

function updateFiles($files, $rootpath) {
    $recordset = new SqliteRecordSet;
    foreach ($files as $file) {
        $record = new SqliteRecord;
        $record->AddAttribute('Path', $file[0], 'TEXT', true);

        print_r($record->AsArray()); // shows nothing       
    }

    $recordset->insertIfNotExist_index();
}

【问题讨论】:

    标签: php arrays object methods


    【解决方案1】:

    $this->attributes 与 $this->_attributes

    您应该始终将错误报告设置为 E_ALL 并打开 display_errors 来开发代码。 php 会在这里通知你你的错误。

    【讨论】:

    • argh 你是对的argh argh argh(只是要注意我花了几个小时在错误的方向上搜索)
    • 附注我有 error_reporting(E_ALL); ini_set('display_errors', '1');但没有显示
    • 要么它从未被设置,要么你有其他代码取消它,或者你已经搞砸了 php 的错误处理程序。
    猜你喜欢
    • 1970-01-01
    • 2010-10-17
    • 2017-11-01
    • 2015-02-12
    • 2017-10-24
    • 2018-10-21
    • 1970-01-01
    • 1970-01-01
    • 2011-10-14
    相关资源
    最近更新 更多