I would want to write the following code without switch, if else or the ternary operator. The code is shown below:
switch (type){
case 'bed':
function create{
return new Bed($customer, $price, $dimensions );
}
break;
case 'desk':
function create{
return new Desk($customer, $price, $dimensions);
}
break;
case 'chair':
function create{
return new Chair($customer, $price, $dimensions, $type );
}
break;
}
4
Answers
You can make the code more concise by returning a new instance of the class by using class name stored in
$type
. For calling the constructor with different parameters, make use of splat operator by collecting the params in an array.If you want to call another class here, you can set the classes you want to global. Then in the functions below, you can call them from there using global.
Example output:
you can use the same code in if else statement like below .
if == do not work try to add === instead
📎 – Looks like you’re trying to write a factory function.
Instead of using a conditional, you can create a list of allowed types mapping to class creator functions.
Requires PHP 8.1.0 or later
https://3v4l.org/fDuKG#v8.1.12