我有一个Facade(在这种情况下是一个单例),我使用ServiceProvider
注册它:
服务提供商
use App;
class FacilityServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->singleton('Facility', function(){
return new Facility();
});
// Shortcut so developers don't need to add an Alias in app/config/app.php
$this->app->booting(function()
{
$loader = \Illuminate\Foundation\AliasLoader::getInstance();
$loader->alias('Facility', 'CLG\Facility\Facades\FacilityFacade');
});
}
}
门面
use Illuminate\Support\Facades\Facade;
class FacilityFacade extends Facade {
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor() { return 'Facility'; }
}
现在,我希望在Facility
类中包含静态变量:
Facility.php
class Facility
{
public static $MODEL_NOT_FOUND = '-1';
public function __construct() { ... }
}
但是当我使用Facility::$MODEL_NOT_FOUND
时,我会得到Access to undeclared static property
。
我做错了什么?
答案 0 :(得分:2)
那是因为Facade类只将方法调用“重定向”到底层类。因此您无法直接访问属性。最简单的解决方案是使用getter方法。
class Facility
{
public static $MODEL_NOT_FOUND = '-1';
public function __construct() { ... }
public function getModelNotFound(){
return self::$MODEL_NOT_FOUND;
}
}
替代方法是编写自己的Facade类,该类从Illuminate\Support\Facades\Facade
扩展并使用magic methods直接访问属性