Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make arguments as an optional in an abstract function

Tags:

php

Lets say I have these classes:

abstract class Car
{
    abstract public function handle(array $data);
}

class CarA extends Car 
{
    public function handle(array $data)
    {
        echo $data['color'];
    }
}

$car= new CarA();
// Here I can pass args as an array
$car->handle([
    "color" => "white"
]);

Which works fine.

The problem:

Now I don't want to pass any args

class CarB extends Car 
{
    public function handle()
    {
        echo 'CarB';
    }
}

$car= new CarB();
// Here I dont wnat to pass any args, I just want to call the method.
$car->handle();

Which doesn't work. I face an error: must be compatible with

What I want?

I want the 'handle' function to work only when array data is passed or none.

like image 521
rook99 Avatar asked Mar 27 '26 03:03

rook99


1 Answers

As stated by @jacki360, the closest you will get is to use func_get_args().

abstract class Car
{
    abstract public function handle();
}

class CarA extends Car 
{
    public function handle()
    {
        $args = func_get_args();
        if ( count($args) && is_array($args[0]) ) {
            $data = $args[0];
            echo $data['color'];
        }
    }
}
class CarB extends Car
{
    public function handle()
    {
        echo self::Class . "\n";
    }
}

$car= new CarA();
// Here I can pass args as an array
$car->handle([
    "color" => "white"
]);
$car2 = new CarB;
$car2->handle();
like image 88
ryantxr Avatar answered Mar 29 '26 15:03

ryantxr