Reputation: 10328
Let's say I have a function like:
function get_param ($param1, $param2 = 'value2', $start = 0, $end = 0){
//do stuff with params
}
And I call it different times within an html page that has two ajax POST-call to a php script.
The first ajax call pass just the first parameter (param1) and the second one pass all parameters (param1, param2, start, end). I'm trying to call the get_param()
function passing the first parameter (param1) always and the others just if they are inside the call ( inside the $_POST
array). Otherwise the function has to use his default.
This is my try but it doesn't work.
<?php
if($_POST){
include_once '../includes/functions.php';
if(isset($_POST['param2'])) $param2 = $_POST['param2'];
else $param2 = null;
if(isset($_POST['start'])) $start = $_POST['start'];
else $start = null;
if(isset($_POST['end'])) $end = $_POST['end'];
else $end = null;
$result = get_param($_POST['param1'], $param2, $start, $end);
echo $result;
}
?>
Upvotes: 0
Views: 100
Reputation: 2247
Default arguemnts only used when you don't pass an argument in its place.
$result = get_param($_POST['param1']);
The function would have these values: get_param($_POST['param1'], 'value2', 0, 0)
If you want to do it with null s, like in your code, then you need to check the value of the argument. Like this:
function get_param ($param1, $param2, $start, $end){
$param2 = ($param2 == null) ? 'value2' : $param2;
$start = ($start == null) ? 0 : $start;
$end = ($end== null) ? 0 : $end;
}
Upvotes: 2