1

I need some help. I have a working class and I can use a foreach() to display the public variables:

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";
}

produces:

a => 3
b => 5

Now my problem arises when I want to have an array of 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";
}

produces:

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

How can I loop through the all the elements of the $class array? Any help would be great!

3 Answers 3

5

Your class doesn't implemen the __toString() method, so there's no way for PHP to automatically convert your MyClass to a string when you try to print it:

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

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

You'd need to add ANOTHER loop to iterate over the class's members:

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

... or implement a __toString() method do whatever obj->string conversion you do want.

Sign up to request clarification or add additional context in comments.

Comments

2

You need to have two foreach's

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";
    }
}

Comments

0

Use 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();

Result:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.