Quickly create an empty stdClass object in PHP

📅 — 🧮 112 words — 🏷️
🔗 Permalink

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.

<?php
$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!


comments powered by Disqus

My first experience with PagodaBox
My first experience with...
Get IP range by CIDR notation
Get IP range by CIDR notation
Find any post in the archive.