gerben.dev

Quickly create an empty stdClass object in PHP

For when you need the scaffolding of an empty PHP class object

I was working on a Laravel project and had to work with a Eloquent ORM object; I then needed to create an empty stdClass object.

There's a chance that a person is not known and being lazy I wanted to fill the form anyway with my Person object, so I needed a mockup of that object.

$person = (object) array_fill_keys(
    array('firstname', 'lastname', 'email', 'photo'),
    ''
);

I'd say this solution is quick and dirty.. but frankly, it's not that dirty at all!

In short, this one-liner, creates an array with the 4 keys provided and gives them an empty value ('') then we just typecast it into an object. Done!

Leave a note

This website uses WebMentions and ActivityPub (via brid.gy), you can respond to this post by linking from your page or replying directly to the Fediverse post.

WebMention

or manually.

Fediverse

On the Fediverse or BlueSky you can search for the URL https://gerben.dev/posts/create-empty-stdclass-in-php or search for my handle @gerben.dev@gerben.dev.

View source

✨ It's dangerous out there, please take some space dust! ✨
This work is licensed under CC BY-NC-SA 4.0 | πŸ€– No AI | πŸ“Š Uptime Status