2012-05-12 82 views
1

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

$这个 - >属性VS $此 - > _属性

你应该总是发展与错误报告设置为E_ALL和display_errors设置代码。 PHP会在这里通知你你的错误。

+0

* argh *你是对的* argh argh argh *(只是为了说明我花了几个小时在这个错误的方向搜索) – edelwater

+0

p.s.我有error_reporting(E_ALL); ini_set('display_errors','1');但没有显示 – edelwater

+0

或者它没有设置,或者你有其他代码未设置,或者你用php的错误处理程序。 – goat