Laravel:不能在php速记数组中使用helper [重复]

This question already has an answer here:

PHP version 5.6. Code:

protected $siteServices = [
        1 => [
            'title' =>  'Consulting',
            'key'       =>  'service',
            'description'   =>  '',
            'file'  =>  asset('assets/img/sample/image1.jpg'), // throws error on this line
        ],
];

Error: PHP Parse error: syntax error, unexpected '(', expecting ']'

What would be a possible fix for this?

Edit Solved by moving the variable in the running function instead of making it protected. Also can be solved by declaring the empty variable first then set the values in __constructor()

</div>

It could be done but it in a different way. I have listed two different methods.

First method

protected $siteServices = [
    1 => [
        'title' =>  'Consulting',
        'key'       =>  'service',
        'description'   =>  '',
        'file'  =>  ['asset', 'assets/img/sample/image1.jpg'] // throws error on this line
    ]
];

I replaced the function call with an array assigned to the file key in this array. So, now, you'd be wondering how you could call the asset function, yeah? It is pretty simple.

While you are looping through that array, you can do this:

call_user_func($siteServices[1]['file'][0], $siteServices[1]['file'][1]);

So, what are we doing here?

Firstly, we set an array to the file key where the first element of the array is the name of the function, while the other element is the value for the parameter that needs to be passed to the function defined previously.

So, using the PHP's call_user_func function, you can call functions giving their name and the parameters. I hope this helps you out.


Second method

I am pretty sure you will have a setter function for this property. Therefore, you could do something like this:

public function setSiteService($title, $key, $description, $file)
{
    $file = asset($file);

    $service = [
        'title' => $title,
        'key' => $key,
        'description' => $description,
        'file' => $file
    ];

    $this->siteServices[] = $service;
}

So, the setter does the processing part for you. Hardcoding arrays is not at all a good idea, you should definitely populate through some mechanism.