Assign array argument to class property


#1

Hi friends,

I am using the following line of code to assign an array argument to a class property, but I get an error. Thanks !!! Parse error: syntax error, unexpected ‘?’ in C:\wamp64\www\chain_gang\private\classes\bicycle.class.php on line 30.

$this->brand = $args[‘brand’] ?? ‘’;


#2

Try just $this->brand=$args[‘brand’];
Have no idea why you have the ??" in there!


#3

Hi there,

@ErnieAlex Most likely the reason the null coalesce operator (??) was there, is the moment $args[‘brand’] does not exist in the array, PHP will throw an exception: “Array key ‘brand’ not found”.

Using the null coalesce operator is the best case here, but you should be using PHP 7.*, and looking at the error message, it looks like you aren’t executing the PHP code with a PHP version of 7 or higher.

More info on the null coalesce operator


#4

So, with the operator not available, you are looking at using a ternary for assignment. Something like,

$this->brand= isset($args[‘brand’]) ? $args[‘brand’] : null;