我有一个助手文件夹在我的项目根(所以,外面app/文件夹)。在我的作曲家。json我自动加载它:
"autoload": {
"classmap": [
"app/Http/Controllers",
"app/Models",
"database",
"libraries",
"helpers" // <- Helpers autoloaded here
],
...
},
helper的方法是静态的,它们可以在视图和控制器中正常工作。现在我尝试在第二个helper (Helper_2.php)中使用一个helper (Helper_1.php),如下所示:
class Helper_2 {
protected static $value = Helper_1::getValue();
...
}
但是在声明$value
字段的那一行,我得到了一个错误:
语法错误,意想不到的"(",希望","或";"
我不知道为什么会发生这种情况。语法显然是正确的
更新 - Helper_1.php代码:
class Helper_1 {
public static function getValue() {
$result = '';
switch (Storage::getDefaultDriver()) {
case 'local':
$result= URL::to('/');
break;
case 's3':
$path = Storage::getDriver()->getAdapter()->getClient()->getObjectUrl(env('S3_BUCKET'), '');
break;
}
return $result.'/';
}
}
PHP无法解析初始化式中的非平凡表达式。
你可以这样做:
class Helper_2 {
protected static $value;
}
Helper_2::$value = Helper_1::getValue();
或:
class Helper_2 {
protected static $value;
static function init()
{
self::$value = Helper_1::getValue();
}
}
Helper_2::init();
语法显然是正确的。
它不是。您不能在类属性定义中使用方法调用,因此以下内容是不正确的:
protected static $value = Helper_1::getValue();
您只能使用简单的数据类型,如整数,字符串,数组等