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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With