How to create an empty object in PHP: simple ways and best practices
Hello colleagues! I'm new to PHP (migrating from JavaScript) and ran into a problem. In JS I can just write `let obj = {};` and get an empty object, then add properties to it. In PHP I expected something similar, but the simple code `$obj = {};` throws a syntax error.
I need to create an object that I will fill dynamically in a loop. For example, when processing data from a CSV file, I want to collect an object with some metadata:
```php
$meta = new stdClass();
$meta->title = "Article";
$meta->views = 0;
$meta->tags = [];
```
But it seems to me that using `stdClass` is some kind of hack. Is there a more elegant way? I tried `$obj = (object) [];` — it works, but I'm not sure how correct it is. Also: how do I then check if the object is empty? In JS I would do `Object.keys(
No answers yet.
Log in to leave an answer