调用对象数组的方法?

时间:2012-05-12 19:26:18

标签: php arrays object methods

如何从一组对象(包含对象数组)中调用方法。我读到: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();
}

1 个答案:

答案 0 :(得分:1)

$ this->属性vs $ this-> _attributes

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