Creating a php function with predefined values ​​for a parameter

Let's say I have the following method:

public function chooseCar($car) { return 'You chose this car: ' . $car; } 

I need to set specific values ​​so that I can pass selectCar in the $ car argument, for example, let the developer choose between "Mercedes", "BMW" and "Ford", can this be done in php?

+6
source share
6 answers

You can try to execute the code below.

 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" } } 
+1
source

I have one approach for this.

In the function itself, create an array.

And check if the parameter is $car in_array ()

 public function chooseCar($car = '') { $allowedCars = array('Mercedes', 'BMW', 'Ford'); if (! in_array($car, $allowedCars)) { return FALSE; } return 'You chose this car: ' . $car; } 
+1
source

You can check if the parameter is an "acceptable value" as follows:

 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'); } 
+1
source

Something like this will 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!'); } } 
0
source

As someone suggested, use an enumeration, this way you will be better programmed, and you are sure that your function is called correctly with the car, and not something else:

 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.\n"; } elseif (CarBrand::AUDI == $car) { echo "Audi.\n"; } } $car = new CarBrand(CarBrand::MERCEDES); chooseCar($car); 
0
source

Under the code below, if you know the 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 the php in_array () or array_search () functions, as described in other answers.

-one
source

All Articles