Let's say I have the following method:
public function chooseCar($car)
{
return 'You chose this car: ' . $car;
}
I need to set specific values for what can be passed to chooseCar in the $car argument, for example let the developer choose between 'Mercedes', 'BMW' and 'Ford', is that doable in php?
You may try below code.
public function chooseCar($car)
{
$predefined_vals = array( 'Mercedes', 'BMW', 'Ford');
if(in_array($car,$predefined_vals)){
return 'You chose this car: ' . $car;
}else{
return "undefined values chosen"
}
}
Something along the lines of this would help you with a fixed list of available cars:
<?php
class Cars
{
private $availableCars = ['Merc', 'Ford'];
public function chooseCar($car)
{
if (in_array($car, $this->availableCars)) {
return 'You chose this car: ' . $car;
}
throw new \Exception('Invalid car chosen!');
}
}
By below code if you know types of cars
public function chooseCar($car)
{
switch($car)
{
case 'BMW':
return 'You chose this car: ' . $car;
break;
case 'Ford':
return 'You chose this car: ' . $car;
break;
default:
return 'Soory, Your car not exist in the list';
}
}
You can also use php in_array() or array_search() functions as describe in other answers.
I have one approach for this.
In the function itself, create an array.
And check if the parameter $car
is in_array()
public function chooseCar($car = '') {
$allowedCars = array('Mercedes', 'BMW', 'Ford');
if (! in_array($car, $allowedCars)) {
return FALSE;
}
return 'You chose this car: ' . $car;
}
You can check if the parameter is an "acceptable value" like this:
var $acceptableCars = [ 'Mercedes', 'BMW', 'Ford'];
function chooseCar($car) {
if (in_array($car, $acceptableCars)) {
return 'You chose this car: ' . $car;
}
throw new Exception('Not a valid car');
}
As someone suggested, use an enum, this way you're program will be better designed, and you're sure your function is called properly with car, not another thing:
class CarBrand extends SplEnum {
// No value, then undefined
const __default = 1;
const MERCEDES = 1;
const AUDI = 2;
}
function chooseCar(CarBrand $car) {
if (CarBrand::MERCEDES == $car) {
echo "Mercedes.
";
} elseif (CarBrand::AUDI == $car) {
echo "Audi.
";
}
}
$car = new CarBrand(CarBrand::MERCEDES);
chooseCar($car);