phpphp-8.1

I get a "Non static method" error after upgrading to PHP 8.1


I have the following PHP error after upgrading from PHP7.4 to PHP8.1

$result = CarsDAO::selectCarsByColor($idCar, self::CARS_PER_PAGE, 0);

Non static method 'selectCarsByColor' should not be called statically

Any ideas how to rewrite this to be OK?


Solution

  • As the error says, the method is not static in the CarsDAO class, so you should call it on an instance.

    $car    = new CarsDAO();
    $result = $car->selectCarsByColor($idCar, self::CARS_PER_PAGE, 0);
    

    Dirty one-liner

    $result = (new CarsDAO)->selectCarsByColor($idCar, self::CARS_PER_PAGE, 0);
    

    or repair the class by making the method static adding the static keyword in front of the method declaration. Read about static in the manual.

    class CarsDAO {
        public static function selectCarsByColor($idCar, $carsPerPage, $zeroThing) {
        // code here
        }
    }