PHP function with variable as default value for a parameter PHP function with variable as default value for a parameter php php

PHP function with variable as default value for a parameter


No, this isn't possible, as stated on the Function arguments manual page:

The default value must be a constant expression, not (for example) a variable, a class member or a function call.

Instead you could either simply pass in null as the default and update this within your function...

function actionOne($id=null) {    $id = isset($id) ? $id : $_GET['ID'];    ....}

...or (better still), simply provide $_GET['ID'] as the argument value when you don't have a specific ID to pass in. (i.e.: Handle this outside the function.)


function actionOne( $id=null ) {    if ($id === null) $id = $_GET['ID'];}

But, i would probably do this outside of the function:

// This line would change, its just a for instance$id = $id ? $id : $_GET['id'];actionOne( $id );


You should get that id before you call the function. Checking for the existence of the parameter breaks encapsulation. You should do something like that:

if (isset($_GET["ID"]){    $id = $_GET["ID"];}else{    //$id = something else}function doSomethingWithID($id){    //do something}