$resp = new stdClass();
$resp->first_name->type = "select";
$resp->first_name->required = 'true';
$resp->first_name->type_meta->options[0] = "opt 1";
$resp->first_name->type_meta->options[1] = "opt 2";
$resp->first_name->type_meta->options[2] = "opt 3";
$resp->last_name->type = "text";
$resp->last_name->required = 'true';
$resp->last_name->type_meta=new stdClass();
Why does my script won't work on my php file but works on w3schools php try it compiler. The error I get is Fatal error: Uncaught Error: Attempt to assign property "type" on null
Even though I am using stdClass() to create an object so why it gives null for type field.
CodePudding user response:
You need to create the sub-properties first. A property without a value is null, so you need to make it an stdClass as well and then you can go.
$resp = new stdClass();
$resp->first_name = new stdClass();
$resp->first_name->type = "select";
$resp->first_name->required = 'true';
$resp->first_name->type_meta = new stdClass();
$resp->first_name->type_meta->options[0] = "opt 1";
$resp->first_name->type_meta->options[1] = "opt 2";
$resp->first_name->type_meta->options[2] = "opt 3";
$resp->last_name = new stdClass();
$resp->last_name->type = "text";
$resp->last_name->required = 'true';
$resp->last_name->type_meta=new stdClass();
CodePudding user response:
you need to set a value for $resp->first_name
and $resp->last_name
because there values is null or if you are using php 8 you can use null safer operator like this : $resp->first_name?->type = "select";