Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast multiple array elements to object

Tags:

php

I'm trying to create an array containing multiple objects.

I wrote this code (it's a member of an existing class)

public static $Roles = [
    (object) ['code' => 'SO', 'name' => 'Socio'],
    (object) ['code' => 'RESP', 'name' => 'Responsabile zona'],
    (object) ['code' => 'AMM', 'name' => 'Amministratore'],
];

but I get this error:

syntax error, unexpected '(object)' (object) (T_OBJECT_CAST), expecting ')'

on the second line.

I thought this should work, because I already used the same cast syntax to define associative array elements:

return view('edit-headquarter', [
  'hq' => (object)['name' => '', 'id' => 0],
  'submitAction' => 'insert'
]);

I'm doing something wrong?

EDIT: I'm using PHP 5.4.45

I'm not sure, but this can be related as suggested by Martin Persson

like image 974
Andrea Parodi Avatar asked Oct 19 '22 13:10

Andrea Parodi


1 Answers

If you're using PHP version below v5.6, then you will not be allowed to have an expression as a default value for class members. Other than that, I don't see anything wrong with the way you have declared it.

like image 178
marpe Avatar answered Nov 15 '22 04:11

marpe