Home > Software engineering >  In PHP, how can I select 1 of 3 child classes without conditional statements
In PHP, how can I select 1 of 3 child classes without conditional statements

Time:09-23

I have a task where I need to output an object of class Honda or BMW or Tesla, all of which extend the abstract class Car. The output should be based on what input is entered by the user, but no conditional statements are allowed in any part of the code (if-else, switch-case, ternary).

The input options are "Japan", "Germany" and "America", which should respectively output an object of Honda, BMW or Tesla.

What I did initially was try to use ternary operators, but I was told to rework it as ternary operators are still considered conditional.

hon = new Honda;
bmw = new BMW;
tes = new Tesla;

newH = hon->objectify();
newB = bmw->objectify();
newT = tes->objectify();

myCar = newH ?: newB ?: newT;
return myCar;

This was what I did, where objectify() is basically an abstract function implemented differently by each child class, returning null if the input doesn't match, or an object of itself if the input matches.

This submission was rejected. Please what's a better way to make this work?

CodePudding user response:

So make use of associative arrays then like below based on your input and use your input as the key.

<?php

$input = "Japan";

$map= ["Japan" => new Honda(), "Germany" => new BMW(), "America" => new Tesla()];

return $map[ $input ]->objectify();

CodePudding user response:

You could use the value input by the user to look up which class to instantiate using an array to map from one to the other. For example:

$carTypes = array("Germany" => "BMW", "Japan" => "Honda", "America" => "Tesla");
$country = "Germany"; //replace this with actual user input, in your version

$car = new $carTypes[$country]();
$car->objectify();

Demo: https://3v4l.org/0WSLO

See also instantiate a class from a variable in PHP?

  • Related