Converting an empty class variable to an object?

I would like the access RequestParams::$headers as an object.

So instead of:


I can just do:


I have the following in the construct that will take an array and convert it to an object:

public function __construct($array = null){
    if (is_array($array)){
        $data = array_change_key_case($array);
        $object = json_decode(json_encode($data), FALSE);
        $this->headers = $object;
    }else if ($array === null){
        //does not work
        $this->headers = new \stdClass();

I then add objects with:

public function set ($key, $value){
    if (!empty($key) && !empty($value)) {
        return $this->headers->$key = $value;

However if there isn’t an array provided orignally (with data) I get a ’ Attempt to assign property of non-object’ error. I have worked round it by providing a default but whats the correct way to initialise it as an empty object?

edit: update code

Couldn’t you just declare it as an object to begin with?

public $headers = \NULL;

plus a simple way to convert an array to an object would to simply do this

$myObject = (object) $myArray;
1 Like

Sorry for the delay, yep calling as NULL worked thank you.

Wasn’t actually using the json_decode(json_encode) but forgot all about typecasting…

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.