2011-07-14 23 views
1

這裏是我的代碼:如何轉換存儲在對象數組值

class Sub extends DatabaseObject { 

    protected static $table_name="subs"; 
    protected static $db_fields=array('id', 'product_id', 'col1', 'col2', 'col3', 'col4', 'col5', 'col6', 'col7', 'col8', 'col9', 'col10', 'col11', 'col12'); 

    public $id; 
    public $product_id; 
    public $col1; 
    public $col2; 
    public $col3; 
    public $col4; 
    public $col5; 
    public $col6; 
    public $col7; 
    public $col8; 
    public $col9; 
    public $col10; 
    public $col11; 
    public $col12; 

find_subs_on($product_id)函數調用傳遞值成以上的公共變量其他功能。

我的問題是,我想在一個表來顯示上述的值,其內部的<td>

每個COL我是否創建取這些值,並返回一個陣列的類中的功能,然後我FOREACH數組?

我是否在視圖中創建了一個數組,並通過$sub->col1$sub->col2等?

如果有人能指出一個正確的方法來做到這一點的例子,我會愛。非常感謝您的幫助!

回答

1

這可能是你所需要的:get_object_vars($object)

注:將出口僅公共和設置變量

+0

聽起來不錯,但是我把它放在視圖中還是在課堂上?現在我試圖做到這一點: ' public function cols(){ \t \t return self :: get_object_vars(); \t }' –

+1

應該是'return get_object_vars($ this);' –

+0

Glass Robot說的是什麼。 – MeLight

1
<?php 
    class test 
    { 
     function get_variable($var) 
     { 
      return $this->$var; 
     } 

     function set_variable($var, $value) 
     { 
      private $this->$var = $value 
     } 
    } 

    $test = new test; 
    $test->set_variable("foo", "bar"); 
    $variable = $test->get_variable("foo"); 
?> 

或更容易,但壞

<?php 
    class test 
    { 
    } 

    $test = new test; 
    $test->foo = bar; 
    $variable = $test->foo; 
?> 
2

您可以在一個使用的foreach對象,但如果你想要,你可以將一個對象轉換爲一個數組:

$obj = new ClassName; 
$obj_to_array = (array) $obj; 
print_r($obj_to_array);