I have a class with the structure below. And Im trying to call a method of the class with "$this->getTopProds($prodsInfo)" however Im getting an error:
"Cannot use '$this' in non-object context.intelephense(1030)"
And on the page the error is "Non-static method App\JsonResponse\Prod\ProdRender:: getTopProds() cannot be called statically".
Do you know what can be the issue?
class ProdRender
{
public static function hotel(array $prodsInfo): array
{
dd($this->getTopProds($prodsInfo));
}
private function getTopProds(array $prodsInfo)
{
//
}
}
CodePudding user response:
No, we can't use this
keyword inside a static
method. “this” refers to the current instance of the class. But if we define a method as static, the class instance will not have access to it
To keep using the other method call inside the static method you need to change the second method getTopProds
to be static too, and call it with self
self::getTopProds($prodsInfo)
CodePudding user response:
In case you need it try this:
<?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);