1

When declaring variables at the top of a class, does it matter if I do:

private $garbage_values;

instead of:

private $garbage_values = [];

Of course, there will be foreach loops within the class that reference the array, and the array may be empty. Does this matter?

3
  • not really as far as I know. PHP is pretty flexible. But you must always check if it's an array before running it through a foreach if you don't declare it initially as an array. Commented Dec 11, 2016 at 7:42
  • Ah - that's what I meant. So private $value would generate an error if I tried to run a foreach on it when empty? Commented Dec 11, 2016 at 7:58
  • yes. So either make it an empty array so you don't need to check. Or add a check before doing foreach. Anyway, you could easily test these small things in phpfiddle if you don't want to run a script. Commented Dec 11, 2016 at 8:35

1 Answer 1

2

Basically, if you'd want any type of variable to work in a foreach like it should, it should fall into the iterable pseudo-type.

So if you use a variable that does not fall into the iterable pseudo-type, in a foreach an error would spring up.

And in your case, i.e. private $foo; if you leave it like that, it basically contains the value null which does not fall into iterable, so it would fail.

Whereas, if you use private $foo = []; it contains an empty array, which indeed does fall into the iterable pseudo-type and can be used flawlessly in a foreach.

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

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.