Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining class variables with a space

Tags:

php

I'm trying to make a class which has object names with a space in between. Just so I can access them like this:

$object->{'Var name with spaces'};

I've read this topic over here and now know how to access those variables, but I'm not sure how to create a class with these variables. I've tried something like this, but I can't get it to work:

class Hotel
{
    public ${'Var name with spaces'} = 'Some value'; // Fails
}

How would I go and create variables in a class definition containing spaces?

like image 780
Ruben Homs Avatar asked Mar 04 '26 06:03

Ruben Homs


1 Answers

I'm pretty sure you'd have to do this in your constructor, because class properties cannot require runtime evaluation.

class Hotel {
    public function __construct() {
        $this->{'Var name with spaces'} = 'Some value';
    }
}

You can see it working in this demo, but I think the comments have shed enough light on why you shouldn't do this. :)

like image 83
nickb Avatar answered Mar 06 '26 19:03

nickb