在非对象 context.intelephense(1030) 中使用 $this 时出错并且无法静态调用非静态方法

error using $this in non-object context.intelephense(1030) and Non-static method cannot be called statically

我有一个 class 结构如下。我试图用“$this->getTopProds($prodsInfo)”调用 class 的方法,但是我收到一个错误:

 "Cannot use '$this' in non-object context.intelephense(1030)" 

并且页面上的错误是“无法静态调用非静态方法 App\JsonResponse\Prod\ProdRender:: getTopProds()”。

你知道问题出在哪里吗?

class ProdRender
{
    public static function hotel(array $prodsInfo): array
    {

        dd($this->getTopProds($prodsInfo));

    }

   

    private function getTopProds(array $prodsInfo)
    {
        //
    }
}

不,我们不能在 static 方法中使用 this 关键字。 “this”指的是 class 的当前实例。但是如果我们将一个方法定义为静态的,class 实例将无法访问它

要在静态方法中继续使用其他方法调用,您需要将第二个方法 getTopProds 也更改为静态方法,并使用 self 调用它 self::getTopProds($prodsInfo)

如果你需要它试试这个:

<?php
class ProdRender
{
    public function hotel(array $prodsInfo)
    {

        return $this->getTopProds($prodsInfo);

    }
    
    private function getTopProds(array $prodsInfo)
    {
        return $prodsInfo;
    }
}

$ho = new ProdRender();
$response = $ho->hotel(["fadf","ceec"]);
var_dump($response);