phpforeach()与类数组


php foreach() with a class array

我需要一些帮助。我有一个工作类,我可以使用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数组的所有元素?任何帮助都会很棒!

您的类没有实现__toString()方法,因此当您尝试打印MyClass时,PHP无法自动将其转换为字符串:

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->字符串转换。

您需要有两个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";
    }
}

使用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