Arrays in objects

I’m just starting to learn about OOP in PHP. I am wondering about the use of arrays as properties in a class. I have Googled and there is a lot about the difference between objects and arrays and converting arrays to objects, but not much about using an array as a property. I have been able to find out how to do it (I believe you simply write

public $thing();

instead of

public $thing;

when creating the class.)

I am wondering if there are reasons why this is a bad thing to do or whether there are better ways of doing things or if the reason for the lack of information is simply that it is no big deal and there is not much to say about it?

The reason why I am asking is that I am thinking about recoding a little routine I wrote that deals with a number of prices. The user enters the prices, the number of which could be different on different occasions. It seems that an array would be the best way to deal with that. Any comments/pointers welcome, to aid my learning process.

Well for starters the syntax for an array is square brackets, not parenthesis. But read on.

You can certainly use arrays as class properties. That said, an array is no different than any other property. A variable is a variable and can hold anything; as such, you don’t need to use the square brackets in your declaration.

If you want to enforce an array to be in that thing, it’s probably better to declare it as such: (PHP 7.4+)

public array $thing;
public ?array $thing; (if $thing should be nullable.)


Oh, I see - good to know.

All good stuff. Thank you.