New to object oriented programming so excuse me for this very basic question.
I'm working on a Laravel app where I've created a parent Graph class which has two subclasses.
In the parent class, I wanted to hold common functions that I want to use in the sub classes.
Graph:
<?php
namespace App\Graphs;
class Graph
{
public function stringToFloat(?string $string): float
{
if (!$string) {
return 0;
}
return \preg_replace('/[^0-9.-]+/', '', $string);
}
public function concatCosts(array $costs, string $table): string
{
$concatCosts = '';
if (\count($costs)) {
$concatCosts = \array_reduce($costs, function ($carry, $item) use ($table) {
return $carry . ($carry ? '+' : '') . ($table . '.' . $item);
});
}
return '+' . $concatCosts;
}
public function generateColor()
{
return '#' . \str_pad(\dechex(\mt_rand(0, 0xFFFFFF)), 6, '0', \STR_PAD_LEFT);
}
}
Now using these methods like this fails:
<?php
namespace App\Graphs;
use App\User;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
class OrdersGraphs extends Graph
{
public function totalSpendingOverTime(Collection $orders, array $suppliers, string $start, string $end): array
{
$data = DB::table('ordered_items')
->whereBetween('created_at', [$start, $end])
->whereIn('order_id', $orders)
->whereIn('supplier', $suppliers)
->select(
[
'created_at',
DB::raw('SUM(price) as cogs'),
]
)
->orderBy('created_at')
->groupBy('created_at')
->get();
$total = DB::table('ordered_items')->select([DB::raw('SUM(price)')])->get();
$totalInData = $data->reduce(function ($carry, $item) {
return $carry + $this->stringToFloat($item->cogs);
The last line you see above fails and returns the error:
message: "Using $this when not in object context"
I do have the code running by using the static keyword next to the common functions and calling them like Graph:: stringToFloat() but it almost feels wrong. Shouldn't I be able to use $this here?
Thanks,
parent::stringToFloat($item->cogs)