Search code examples
phpstdclass

How to fix new stdClass error


I am trying to understand the new stdClass in terms of sending data to a function, I've created the following code and I'll get an error that's saying Warning: Creating default object from empty value, however, still I get the json data as well. How to fix the error and why I am getting it?

$send = new stdClass();
$send->user->id = '12121212121';
$send->message->attachment->type = 'file';
$send->message->attachment->image = 'png';
$res = process($send);

function process($send){
    $data = json_encode($send);
    print_r($data);
}

Result is looks like this and there is an error above below result as I mentioned it:

{"user":{"id":"12121212121"},"message":{"attachment":{"type":"file","image":"png"}}}


Solution

  • Create stdClass for each reference like this

    $send = new stdClass();
    $send->user=new stdClass();
    $send->user->id = '12121212121';
    $send->message=new stdClass();
    $send->message->attachment=new stdClass();
    $send->message->attachment->type = 'file';
    $send->message->attachment->image = 'png';
    $res = process($send);
    
    function process($send){
        $data = json_encode($send);
        print_r($data);
    }