Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP function with variable as default value for a parameter

By default a PHP function uses $_GET variables. Sometimes this function should be called in an situation where $_GET is not set. In this case I will define the needed variables as parameter like: actionOne(234)

To get an abstract code I tried something like this:

function actionOne($id=$_GET["ID"]) 

which results in an error:

Parse error: syntax error, unexpected T_VARIABLE

Is it impossible to define an default parameter by using an variable?

Edit

The actionOne is called "directly" from an URL using the framework Yii. By handling the $_GET variables outside this function, I had to do this on an central component (even it is a simple, insignificant function) or I have to change the framework, what I don't like to do.

An other way to do this could be an dummy function (something like an pre-function), which is called by the URL. This "dummy" function handles the variable-issue and calls the actionOne($id).

like image 688
The Bndr Avatar asked May 02 '11 16:05

The Bndr


People also ask

Can you assign the default values to a function parameters in PHP?

PHP allows us to set default argument values for function parameters. If we do not pass any argument for a parameter with default value then PHP will use the default set value for this parameter in the function call.

What is the default value of a variable in PHP?

1 Answer. Show activity on this post. Variables that are declared without a value and undefined/undeclared variables are null by default.

Can you assign the default values to a function parameters?

Default parameter in JavascriptThe default parameter is a way to set default values for function parameters a value is no passed in (ie. it is undefined ). In a function, Ii a parameter is not provided, then its value becomes undefined . In this case, the default value that we specify is applied by the compiler.


1 Answers

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.)

like image 75
John Parker Avatar answered Oct 09 '22 07:10

John Parker