Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/269.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Laravel:无法在php速记数组中使用帮助程序_Php_Arrays_Laravel 5 - Fatal编程技术网

Laravel:无法在php速记数组中使用帮助程序

Laravel:无法在php速记数组中使用帮助程序,php,arrays,laravel-5,Php,Arrays,Laravel 5,PHP版本5.6。代码: protected $siteServices = [ 1 => [ 'title' => 'Consulting', 'key' => 'service', 'description' => '', 'file' => asset('assets/img/sample/image1.jpg'), //

PHP版本5.6。代码:

protected $siteServices = [
        1 => [
            'title' =>  'Consulting',
            'key'       =>  'service',
            'description'   =>  '',
            'file'  =>  asset('assets/img/sample/image1.jpg'), // throws error on this line
        ],
];
错误:
PHP解析错误:语法错误,意外的“(”,应为“]”

有什么可能解决这个问题

编辑
通过在运行函数中移动变量而不是使其受保护来解决。也可以通过先声明空变量,然后在
\uu constructor()
中设置值来解决。可以这样做,但方式不同。我列出了两种不同的方法

第一种方法

protected $siteServices = [
    1 => [
        'title' =>  'Consulting',
        'key'       =>  'service',
        'description'   =>  '',
        'file'  =>  ['asset', 'assets/img/sample/image1.jpg'] // throws error on this line
    ]
];
我将函数调用替换为分配给该数组中文件键的数组。因此,现在,您可能想知道如何调用资产函数,是吗?它非常简单

在该数组中循环时,可以执行以下操作:

调用用户函数($siteServices[1]['file'][0],$siteServices[1]['file'][1]);

那么,我们在这里干什么

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

因此,使用PHP函数,您可以调用函数,给出它们的名称和参数。我希望这对您有所帮助


第二种方法

protected $siteServices = [
    1 => [
        'title' =>  'Consulting',
        'key'       =>  'service',
        'description'   =>  '',
        'file'  =>  ['asset', 'assets/img/sample/image1.jpg'] // throws error on this line
    ]
];
我很确定您将为此属性使用setter函数。因此,您可以执行以下操作:

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

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

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

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

只有当他稍后手动处理数组时,这才有效,而不是如果数组是某个框架的一部分,该框架通过某种约定进行处理时,这是最好的。否则,我有另一种方法。但这个问题没有意义,您可以将函数作为值调用,其结果将是value@RoyalBg嗯,这是PHP。你不能指望它的所有功能都能正常工作。我为他尝试了不同的模型函数,但我失败了。我认为call_user_func是一个很好的替代方案,或者我刚刚提出的方法。检查第二种方法。你应该期望它能正常工作rk,人们在实际项目中依赖PHP。是的,第二种方法更好。但是我们需要找到问题的根源,它肯定不是来自函数调用。我相信这不是重复。另一个问题涉及将数据传递给对象,而这个问题的OP试图调用对象中数组内的函数面向上下文。这都是一样的。如果需要初始化这个数组,可以在构造函数中完成。但这很难看@RoyalBg@HassanAlthaf为什么这么难看?这只是constructor调用了您建议的
setSiteService
方法