I have a very annoying problem to solve. I have a method that searches for a code of a sale, it is:
public function findByCode(string $code, string $columns = "*"): ?Sales
{
$find = $this->find("code = :code", "code={$code}", $columns);
return $find->fetch(true);
}
When I try to call him that:
$sales = (new Sales())->findByCode(client()->code);
It shows me the following error:
Uncaught TypeError: Return value of Source\Models\Sales::findByCode() must be an instance of Source\Models\Sales or null, array returned in
How to solve this?
CodePudding user response:
You are making the findByCode
function restrict to return data with type Sales
and when you are using return $find->fetch(true);
it will return some array of that's type is not compatible with Sales
so PHP is complaining here about that. so just make a new object of Sales
and return it.
The code should be some thing like this:
public function findByCode(string $code, string $columns = "*"): ?Sales
{
$find = $this->find("code = :code", "code={$code}", $columns);
$result = $find->fetch(true);
return new Sales($result);
}
So the Sales
class can get the data and assign them to its properties and act as a DTO
or something.