在 Laravel 控制器中不在对象上下文中时使用 $this
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40929670/
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
Using $this when not in object context in a Laravel controller
提问by Rohansin
I created a public static function in a controller and I need to access a class property which is set on the constructor. I normally use $this->something
to access such class properties, but this time, I got this error:
我在控制器中创建了一个公共静态函数,我需要访问在构造函数上设置的类属性。我通常$this->something
用来访问这样的类属性,但这一次,我收到了这个错误:
Using
$this
when not in object context
使用
$this
时没有对象上下文
Here's the code:
这是代码:
public static function PayExecute() {
$paymentId = Input::get('paymentId');
$PayerID = Input::get('PayerID');
$cont = $this->apiContext;
}
回答by V. Kovpak
You need $apiContext
be declared as static property, and you need use static
of self
keyword. Something like this:
你需要$apiContext
声明为静态属性,你需要使用static
的self
关键字。像这样的东西:
class YourController extends BaseController
{
private static $apiContext = '';
public static function PayExecute()
{
$paymentId = Input::get('paymentId');
$PayerID = Input::get('PayerID');
$cont = static::$apiContext;
}
}
BTW: Be aware about fact that static
is late static binding.
顺便说一句:注意static
后期静态绑定的事实。
回答by NaeiKinDus
You cannot use "$this" in static methods. You do have access to "self::" though, but remember that you cannot access methods / properties that require the current class to be instanciated.
您不能在静态方法中使用“$this”。不过,您确实可以访问“self::”,但请记住,您无法访问需要实例化当前类的方法/属性。
回答by Sagar Rabadiya
you have to create new instance and then can access its property
您必须创建新实例,然后才能访问其属性
public static function PayExecute() {
$paymentId = Input::get('paymentId');
$PayerID = Input::get('PayerID');
$cont = (new static)->apiContext;
}