Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - assigning values in a function argument - good practice?

Tags:

php

Setting variable values inside a function call - I don't see this a lot, is this considered good practice?

function myUpdate($status){
    ...
}

myUpdate($status = 'live');

I personally like it because it's more descriptive. I see it more frequently the other way around, ie., assigning a default value in the function definition.

like image 250
Owen Avatar asked Mar 11 '26 17:03

Owen


2 Answers

That's a very bad idea, because it's basically code obfuscation. php does not support keyword arguments, and that can lead to weird stuff. Case in point:

function f($a, $b){
    echo 'a: ' . $a . "\n";
    echo 'b: ' . $b . "\n";
}
f($b='b-value', $a='a-value');

This program does not only output

a: b-value
b: a-value

but also defines the variables $b and $a in the global context. This is because

f($b='b-value', $a='a-value');
// is the same thing as ...
$b = 'b-value';
$a = 'a-value';
f($b, $a);

There are a few good practices one can do to make remembering method arguments easier:

  • Configure your editor/IDE to show the signature of functions on highlight.
  • If a function has lots of arguments that describe some kind of state, consider moving it into an *objec*t (that holds the state instead)
  • If your function just needs lots of arguments, make it take an array for all non-essential ones. This also allows the method caller not to worry at all about the multitude of options, she just needs to know the ones she's interested in.
like image 64
phihag Avatar answered Mar 13 '26 08:03

phihag


All kidding aside, seriously why do you use it? You have to realize it's something totally different than assigning a default value. What you're doing here is assigning the value to a variable, and then passing that variable to the function. The result is, that after the function call, the $status varialbe is still defined.

myUpdate( $status = 'live' );
echo $status; // "live"

Even if this is what you want, I'd say it's less descriptive than just splitting it out in two lines.

like image 27
Rijk Avatar answered Mar 13 '26 07:03

Rijk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!