Laravel:不能在php简写数组中使用helper



PHP版本5.6。代码:

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

错误:PHP Parse error: syntax error, unexpected '(', expecting ']'

对此有什么可能的解决方案?

编辑通过在运行函数中移动变量而不是使其成为protected来解决。也可以通过先声明空变量,然后在__constructor() 中设置值来解决

这是可以做到的,但方式不同。我列出了两种不同的方法。

第一种方法

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

我用分配给该数组中文件键的数组替换了函数调用。所以,现在,你可能想知道如何调用资产函数,是吗?这很简单。

当你在这个数组中循环时,你可以这样做:

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

那么,我们在这里干什么?

首先,我们将一个数组设置为文件键,其中数组的第一个元素是函数的名称,而另一个元素是需要传递给之前定义的函数的参数值。

因此,使用PHP的call_user_func函数,可以调用给定名称和参数的函数。我希望这能帮助你。


第二种方法

我确信您将为该属性提供一个setter函数。因此,你可以这样做:

public function setSiteService($title, $key, $description, $file)
{
    $file = asset($file);
    $service = [
        'title' => $title,
        'key' => $key,
        'description' => $description,
        'file' => $file
    ];
    $this->siteServices[] = $service;
}

因此,setter为您完成处理部分。对数组进行硬编码根本不是一个好主意,您肯定应该通过某种机制进行填充。

最新更新