PHP Function with Variable as Default Value for a Parameter

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

Having a PHP function use a global variable as a default?

You could use a constant. Define it at the top of a file and let your functions use that. E.g.

define('CUSTOM_TIMEZONE', 'Mountain');

function tell_time($values, $timezone = CUSTOM_TIMEZONE) {
// Your code here
}

Just change the constants value and it's changed everywhere.

Using Default Arguments in a Function

I would propose changing the function declaration as follows so you can do what you want:

function foo($blah, $x = null, $y = null) {
if (null === $x) {
$x = "some value";
}

if (null === $y) {
$y = "some other value";
}

code here!

}

This way, you can make a call like foo('blah', null, 'non-default y value'); and have it work as you want, where the second parameter $x still gets its default value.

With this method, passing a null value means you want the default value for one parameter when you want to override the default value for a parameter that comes after it.

As stated in other answers,

default parameters only work as the last arguments to the function.
If you want to declare the default values in the function definition,
there is no way to omit one parameter and override one following it.

If I have a method that can accept varying numbers of parameters, and parameters of varying types, I often declare the function similar to the answer shown by Ryan P.

Here is another example (this doesn't answer your question, but is hopefully informative:

public function __construct($params = null)
{
if ($params instanceof SOMETHING) {
// single parameter, of object type SOMETHING
} elseif (is_string($params)) {
// single argument given as string
} elseif (is_array($params)) {
// params could be an array of properties like array('x' => 'x1', 'y' => 'y1')
} elseif (func_num_args() == 3) {
$args = func_get_args();

// 3 parameters passed
} elseif (func_num_args() == 5) {
$args = func_get_args();
// 5 parameters passed
} else {
throw new \InvalidArgumentException("Could not figure out parameters!");
}
}

How do you reference another parameter as the default value of a parameter in a function?

Best is

if ($href == null)
$href = $file;

Default value for reference argument in PHP function

You can check the number of arguments passed into the function using func_num_args()

function fn (&$ref = null) {
echo func_num_args().PHP_EOL;
if ($ref === null)
echo "ref null".PHP_EOL;
else
echo "ref not null".PHP_EOL;
}
$var = null;
fn($var);
fn();

will give

1
ref null
0
ref null

PHP SET default argument in function as static variable

You can make a workaround in this case:

public static function isUserExist($CurrentUID = false)
{
if(!$CurrentUID)
$CurrentUID = UserControl::$CurrentUID;
....
}

PHP Function Array Default Values?

You can only use scalar types for the default values of function arguments.

You can also read this in the manual: http://php.net/manual/en/functions.arguments.php#functions.arguments.default

And a quote from there:

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

EDIT:

But if you still need this value as default value in the array you could do something like this:

Just use a placeholder which you can replace with str_replace() if the default array is used. This also has the advantage if you need the return value of the function in the default array multiple times you just need to use the same placeholder and both are going to be replaced.

public function create(
$data = [
"user-id" => "::PLACEHOLDER1::",
//^^^^^^^^^^^^^^^^ See here just use a placeholder
"level" => '1',
"ignore-limits" => '0',
]){
$data = str_replace("::PLACEHOLDER1::", Auth::id(), $data);
//^^^^^^^^^^^ If you didn't passed an argument and the default array with the placeholder is used it get's replaced
//$data = str_replace("::PLACEHOLDER2::", Auth::id(), $data); <- AS many placeholder as you need; Just make sure they are unique
//...
}

Another idea you could do is set a default array which you can check and then assign the real array like this:

public function create($data = []){
if(count($data) == 0) {
$data = [
"user-id" => Auth::id(),
"level" => '1',
"ignore-limits" => '0',
];
}
//...
}

PHP Default Function Parameter values, how to 'pass default value' for 'not last' parameters?

PHP doesn't support what you're trying to do. The usual solution to this problem is to pass an array of arguments:

function funcName($params = array())
{
$defaults = array( // the defaults will be overidden if set in $params
'value1' => '1',
'value2' => '2',
);

$params = array_merge($defaults, $params);

echo $params['value1'] . ', ' . $params['value2'];
}

Example Usage:

funcName(array('value1' => 'one'));                    // outputs: one, 2
funcName(array('value2' => 'two')); // outputs: 1, two
funcName(array('value1' => '1st', 'value2' => '2nd')); // outputs: 1st, 2nd
funcName(); // outputs: 1, 2

Using this, all arguments are optional. By passing an array of arguments, anything that is in the array will override the defaults. This is possible through the use of array_merge() which merges two arrays, overriding the first array with any duplicate elements in the second array.

PHP Using $this- variable as Class Method Parameter Default Value

I'm afraid your IDE is correct. This is because "the default value must be a constant expression, not (for example) a variable, a class member or a function call." — Function arguments

You'll need to do something like this:

class something {

public $somevar = 'someval';

private function somefunc($default = null) {
if ($default === null) {
$default = $this->somevar;
}
}
}

This can also be written using the ternary operator:

$default = $default ?: $this->somevar;

how to pass current year as default argument in php function

You can't use a function for a default argument value :

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

(extract from PHP doc)

You should set the default value into the function :

function myFunction($month, $year = null) 
{
if(!(bool)$year) {
$year = date('Y');
}
echo $year.', '.$month;
}

myFunction('June', '2006'); // 2006, June
myFunction(3, 2010); // 2010, 3
myFunction('July'); // 2013, July


Related Topics



Leave a reply



Submit