在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:51:12  来源:igfitidea点击:

Using $this when not in object context in a Laravel controller

phplaravelobjectpropertiesstatic

提问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->somethingto access such class properties, but this time, I got this error:

我在控制器中创建了一个公共静态函数,我需要访问在构造函数上设置的类属性。我通常$this->something用来访问这样的类属性,但这一次,我收到了这个错误:

Using $thiswhen 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 $apiContextbe declared as static property, and you need use staticof selfkeyword. Something like this:

你需要$apiContext声明为静态属性,你需要使用staticself关键字。像这样的东西:

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 staticis 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;
}