3

How does one perform a foreach over all the fields of a class, either from within that class or from without? For instance, given the following class:

class Foo
{
    public $a;
    public $b;
    private $c;
    private $d;

    public function __construct($params)
    {
        foreach($params as $k=>$v){
            $this->$k = $v;
        }
    }

    public function showAll()
    {
        $output = array();
        foreach (this as $k=>$v) {    // How to refer to all the class properties?
            $output[$k] = $v;
        }
        return $output;
    }

}

How might the foreach() in the showAll() method refer to the $a, $b, $c, and $d properties?

For that matter, can one get all the public properties from outside the class?

$params = array();
$foo = new Foo($params);

foreach ($foo->allProperties as $f=>$v) {    // how to do this?
    echo "{$f}: {$v}\n";
}
tereško
  • 58,060
  • 25
  • 98
  • 150
dotancohen
  • 30,064
  • 36
  • 138
  • 197
  • `showAll()` returns all the properties if you fix the typo with `$this` (missing dollar sign). The question is a bit unclear. – Jon Mar 29 '13 at 09:12
  • Your class does not have any static properties, so technically the class has no values. Do you mean the object properties? This will work with reflection. – Wolfgang Stengel Mar 29 '13 at 09:17
  • Thank you Wolfgang, I did mean object properties. That would include static members should any exist. – dotancohen Mar 29 '13 at 09:19

6 Answers6

6

As of PHP4 you can use get_object_vars to iterate over public properties of an object.

foreach (get_object_vars($foo) as $f => $v) {
    echo "{$f}: {$v}\n";
}

As of PHP5 you can iterate directly over the object:

foreach ($foo as $f => $v) {
    echo "{$f}: {$v}\n";
}
Shoe
  • 74,840
  • 36
  • 166
  • 272
  • And how is that different over `foreach` [directly on the object](http://php.net/manual/en/language.oop5.iterations.php)? – Jon Mar 29 '13 at 09:16
  • @Jon, `get_object_vars` is compatible with PHP4 as well. I've included it as well. Thanks. – Shoe Mar 29 '13 at 09:17
  • Ι don't see a mention of PHP4 anywhere in the question. Additionally, we are nearing *9 years* since the release of PHP5. – Jon Mar 29 '13 at 09:23
  • I should probably also mention that the code given above *is not valid PHP4*. – Jon Mar 29 '13 at 09:25
  • PHP4 has no visibility specifiers. And it doesn't recognize the `__construct` name as special, although this last one does not produce a compiler error. – Jon Mar 29 '13 at 09:30
  • @Jon, oh yeah, the code of the author is not PHP4, I just wanted to mention that get_object_vars is valid also for PHP4. For future visitors. – Shoe Mar 29 '13 at 09:32
  • 1
    Allow me to remain sceptical about that. – Jon Mar 29 '13 at 09:35
  • "As of PHP5 you can iterate directly over the object:" - I couldn't do that in my setup (php 7.2 (yes old version of php, legacy app, but above v5 that it would supposed to work). Casting to array worked fine though: https://stackoverflow.com/a/5970283/227926 – therobyouknow Dec 02 '22 at 10:54
3

Use Reflection class: Class Reflectionclass Manual ( PHP 5 )

<?php
class Foo {
   public    $foo  = 1;
   protected $bar  = 2;
   private   $baz  = 3;
}

$foo = new Foo();

$reflect = new ReflectionClass($foo);
$props   = $reflect->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED);

foreach ($props as $prop) {
   print $prop->getName() . "\n";
}

var_dump($props);

?>
Alireza
  • 1,428
  • 4
  • 21
  • 33
  • 1
    Thank you Alireza. I was inclined to accept one of the `get_object_vars` answers, but I see that you've really addressed the core of the issue with Reflection. – dotancohen Mar 29 '13 at 09:56
  • 2
    So you were looking for the most complicated solution? ;) – crackmigg Mar 29 '13 at 10:03
2

probably you are looking for get_object_vars()

$params = array();
$foo = new Foo($params);

foreach (get_object_vars($foo) as $f=>$v) {    // how to do this?
echo "{$f}: {$v}\n";
}

you can also use simple object for iteration as of php5. It will also iterate through all public properties

$foo = new Foo($params);

foreach($class as $key => $value) {
print "$key => $value\n";
}

see http://php.net/manual/en/language.oop5.iterations.php

alwaysLearn
  • 6,882
  • 7
  • 39
  • 67
  • Is there something wrong with `foreach` [directly on the object](http://php.net/manual/en/language.oop5.iterations.php)? – Jon Mar 29 '13 at 09:17
2

The only way to get all properties and their values, including the private ones, from outside the object, and without relying on undocumented behaviour or implementation details, is Reflection:

$ref=new ReflectionObject($object);
foreach ($ref->getProperties() as $prop)
{
    $prop->setAccessible(true);
    $name=$prop->getName();
    $value=$prop->getValue($object);
}
Wolfgang Stengel
  • 2,867
  • 1
  • 17
  • 22
1

You can use get_class_vars — Get the default properties of the class You can do like below:

<?php
class myclass {
    var $var1; // this has no default value...
    var $var2 = "xyz";
    var $var3 = 100;
    private $var4; // PHP 5    
    // constructor
    function myclass() {
        // change some properties
        $this->var1 = "foo";
        $this->var2 = "bar";
        return true;
    }
}
$my_class = new myclass();
$class_vars = get_class_vars(get_class($my_class));
foreach ($class_vars as $name => $value) {
    echo "$name : $value\n";
}
?>

For more info just check PHP

Suresh Kamrushi
  • 15,627
  • 13
  • 75
  • 90
0

While you can iterate over public object attributes using get_object_vars, having to do this might be a bad design and a reason to think about your implementation again. The thing you want to do with the attributes of the object most probably belong into the class/object itself, programmatically.

crackmigg
  • 5,571
  • 2
  • 30
  • 40