2013-07-08 67 views
1

我需要一些幫助。我有一個工人階級和我可以用一個foreach()來顯示公共變量:PHP foreach()與類數組

class MyClass { 
    public $a; 
    public $b; 
    function __construct($aX,$bX){ 
      $this->a = $aX; 
      $this->b = $bX; 
    } 
} 

$class = new MyClass(3,5); 
foreach($class as $key => $value) { 
    print "$key => $value</br>\n"; 
} 

生產:

a => 3 
b => 5 

現在我的問題出現時,我想有MyClass的數組:

class MyClass 
{ 
    public $a; 
    public $b; 
    function __construct($aX,$bX){ 
     $this->a = $aX; 
     $this->b = $bX; 
    } 
} 

$class = array(
    "odd"=>new MyClass(3,5), 
    "even"=>new MyClass(2,4) 
    ); 
foreach($class as $key => $value) { 
    print "$key => $value</br>\n"; 
} 

生產:

Catchable fatal error: Object of class MyClass could not be converted to string... 

如何循環遍歷$ class數組的所有元素?任何幫助將是偉大的!

回答

5

你的類不implemen的__toString()方法,所以沒有辦法讓PHP能當您嘗試打印您的MyClass的自動轉換爲字符串:

foreach($class as $key => $value) { 
        ^^^^-- odd or even 
          ^^^^^^--- Object of type MyClass 

    print "$key => $value</br>\n"; 
        ^^^^^^--- try to output object in string context 

你需要添加另一個循環遍歷類的成員:

foreach($class as $key => $myclass) { 
    foreach($myclass as $key2 => $val) { 
     echo ("$key2 => $val"); 
    } 
} 

...或者實現__toString()方法做任何obj->字符串轉換你想要的。

2

你需要有兩個的foreach的

class MyClass 
{ 
    public $a; 
    public $b; 
    function __construct($aX,$bX){ 
     $this->a = $aX; 
     $this->b = $bX; 
    } 
} 

$class = array(
    "odd"=>new MyClass(3,5), 
    "even"=>new MyClass(2,4) 
    ); 
foreach($class as $arr) { 
    foreach($arr as $key => $value){ 
      print "$key => $value</br>\n"; 
    } 
} 
0

使用get_class_vars

<?php 
class C { 
    const CNT = 'Const Value'; 

    public static $stPubVar = "St Pub Var"; 
    private static $stPriVar = "St Pri Var"; 

    public $pubV = "Public Variable 1"; 
    private $priV = "Private Variable 2"; 

    public static function g() { 
     foreach (get_class_vars(self::class) as $k => $v) { 
      echo "$k --- $v\n"; 
     } 
    } 
} 

echo "\n"; 
C::g(); 

結果:

pubV --- Public Variable 1 
priV --- Private Variable 2 
stPubVar --- St Pub Var 
stPriVar --- St Pri Var