1

I pass parameters to a function in PHP. I dont know if the parameter is defined or not. Right now I check if the parameter is defined and cast to null if not before calling the function. Is there a more elegant way to do it by casting or something similar? I want the function default value to be used if the parameter is not defined.

Example:

//Params['x'] may or may not be defined
// I want to use this:
a(params['x']);

//Currently I use this (which I want to avoid) :
a( isset (params['x'])?params['x']:null);


function a (data=null){
// Here I want data to be null  if params['x'] is not defined. 
}

3 Answers 3

3

It is possible if you declare this argument as reference:

function fun(&$param = null) {

}

Keep in mind, that it will also create this entry if it was not present in passed array, so if you have

$x = array('a' => 1);

And you will call fun($x['b']);, your $x will look like

$x = array('a' => 1, 'b' => null);
Sign up to request clarification or add additional context in comments.

Comments

0

For everything which you're not sure exists, there has to be one point where you test that and/or ensure that it exists. You can do that with isset/empty or with an operation that ensures the value exists, like:

$params += array('x' => null);

You should not design your function to work around parameters the caller may not have. If the function requires the parameter then let it require the parameter, period. The sooner you get out of the may-or-may-not-be-there mode in your code the sooner you can require and return defined values, which cuts down on the amount of code you need to write and debug. By that I mean that the only uncertainty should be user input; punch that uncertain user input into a defined form as early as possible, after that your application internally should be strict about what it requires and what it returns and not be uncertain at every single point.

Comments

0

What you have already done does all you need to do.

With this function prototype you are saying, accept whatever parameter may be passed by the caller, or use NULL if nothing is passed.

function a ($data=null){
    if ( $data == null ) {
       // no parameter passed by caller
    }
}

Just forget about all the fussing with the parameters on the call of the function. Its all done for you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.