I, very hackily, create an object of type stdClass as so:

$arr = array(
    'foo' => 'bar',
    'baz' => 'bat'
);

$obj = json_decode(json_encode($arr));

How can I now quickly add a third property to $obj without PHP getting angry?

I completely agree with you with the "hackily" part , but here it is:

$arr = [
                'foo' => 'bar',
                'baz' => 'bat'
            ];

            $obj = json_decode(json_encode($arr));
            $obj->newProperty = "something";
            var_export($obj);
            exit;

$obj->newProperty = "something";

For some reason I thought that PHP didn't allow that without throwing an error?! (Hence the reason for me posting this question). I'm on PHP 8.2/8.3.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.