1

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

4

3 回答 3

5

您的类没有实现 __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->string 转换。

于 2013-07-08T14:51:31.877 回答
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";
    }
}
于 2013-07-08T14:53:40.000 回答
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
于 2016-03-08T11:46:45.093 回答