在 Laravel Facades 中使用静态变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27347953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use static variables in Laravel Facades
提问by Kousha
I have a Facade (in this case a singleton) and I register it using a ServiceProvider
:
我有一个 Facade(在本例中为单例),我使用以下命令注册它ServiceProvider
:
Service Provider
服务提供者
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');
});
}
}
Facade
正面
use Illuminate\Support\Facades\Facade;
class FacilityFacade extends Facade {
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor() { return 'Facility'; }
}
Now, I want to have static variables inside my Facility
class:
现在,我想在我的Facility
班级中有静态变量:
Facility.php
设施.php
class Facility
{
public static $MODEL_NOT_FOUND = '-1';
public function __construct() { ... }
}
but when I use Facility::$MODEL_NOT_FOUND
, I get Access to undeclared static property
.
但是当我使用时Facility::$MODEL_NOT_FOUND
,我得到Access to undeclared static property
.
What am I doing wrong?
我究竟做错了什么?
回答by lukasgeiter
That's because the Facade class only "redirects" method calls to the underlying class. So you can't access properties directly. The simplest solution is using a getter method.
那是因为 Facade 类只将方法调用“重定向”到底层类。所以你不能直接访问属性。最简单的解决方案是使用 getter 方法。
class Facility
{
public static $MODEL_NOT_FOUND = '-1';
public function __construct() { ... }
public function getModelNotFound(){
return self::$MODEL_NOT_FOUND;
}
}
The alternative would be to write your own Facade class that extends from Illuminate\Support\Facades\Facade
and make use of magic methodsto access properties directly
另一种方法是编写您自己的 Facade 类,该类扩展自Illuminate\Support\Facades\Facade
并利用魔术方法直接访问属性