0

I know that iteration over an object is equal to iterating over the visible properties of the class.

class MyClass
{
    public $var1 = 'value 1';
    public $var2 = 'value 2';
    public $var3 = 'value 3';

    protected $protected = 'protected var';
    private   $private   = 'private var';
}

$class = new MyClass();

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

I'm curious to know why iteration over an object that doesn't implement any interface causes iteration over its visible variables? And what is the use case of this ability?

Nico Haase
  • 11,420
  • 35
  • 43
  • 69
hoseinz3
  • 618
  • 4
  • 13
  • 5
    What feature are you talking about specifically? It doesn't seem clear from your question. – Script47 Mar 06 '19 at 09:01
  • Not sure if the above code would work as you expect it to. – Anurag Srivastava Mar 06 '19 at 09:03
  • @AnuragSrivastava why not try? – splash58 Mar 06 '19 at 09:04
  • @Script47I mean why iterate over an object that doesn't implement any interface cause iterate over its visible variables – hoseinz3 Mar 06 '19 at 09:06
  • Do you mean *Why* because "Why have this ability?" or *Why* because "Why does this work this way?" – Martin Mar 06 '19 at 09:09
  • What do you mean by "use case"? If you have none, that's fine. There are tons of features in PHP that I've never used, but I would not question that there is anybody else out there who has – Nico Haase Mar 06 '19 at 09:13
  • @Martin I mean why have this ability? or is there any use case that people use to iterate over the object to iterate through its visible properties? – hoseinz3 Mar 06 '19 at 09:17
  • 2
    Object is a collection of properties and methods. Built-in control structure `foreach` allows you to iterate over the array items, and visible properties in object and that is built in feature. This is related with your question https://stackoverflow.com/questions/10057671/how-does-php-foreach-actually-work – Nikola Kirincic Mar 06 '19 at 09:22

1 Answers1

3

As far as you have declared class structure it's usually useless or at least a bad practice.

But PHP also allows you to dynamically create properties on objects, so its structure isn't implied by class definition.

You could do:

$class = new MyClass();
$class->nonExistingProperty = 123;

And then iteration over this object would return nonExistingProperty too.

That is a bad practice, but it is possible. It is sometimes used on containers for view data (Zend 1 as far as I remember).

Also there's a predefined stdClass which is designed to create "dynamic objects". For example it's used by json_decode() function.

So for example in case of decoding JSON document you may want to iterate over its properties without knowledge about its structure (it might be dynamic too).

Jakub Matczak
  • 15,341
  • 5
  • 46
  • 64