While in general hints are a good thing, there's a situation which I find pretty annoying and was wondering if there's an easy way around it.
Consider a function which has an output-only variable:
function dumb_foo($param1, $param2, &$out = null) {
$out = $param1.'||'.$param2;
return $param1*$param2;
}
Now making a call such as:
dumb_foo(5, 6, $my_out);
Results in a hint even though it's filled by the function. So yes, it's possible to initialize the variable first
$my_out = null;
dumb_foo(5, 6, $my_out);
but it's redundant.
Is there any other way to avoid the hint in this situation without removing it completely or adding an unneeded initialization?
In computing, an uninitialized variable is a variable that is declared but is not set to a definite known value before it is used. It will have some value, but not a predictable one. As such, it is a programming error and a common source of bugs in software.
An uninitialized variable has an undefined value, often corresponding to the data that was already in the particular memory location that the variable is using. This can lead to errors that are very hard to detect since the variable's value is effectively random, different values cause different errors or none at all.
Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type.
To create a variable without an initial value, simply don't include an initial value: // This creates an uninitialized int int i; The value in an uninitialized variable can be anything – it is unpredictable, and may be different every time the program is run.
To the best of my knowledge, I think the best way is to first look at how pass by reference actually works.
case 1: Referenced variable $in
already initialized but parameter$out
NOT initialized
function increment(&$out) {
$out++;
}
$in = 4 ; //NOTE: already initialized
increment($in);
echo $in; //add up to 5
case 2: Referenced variable $in
NOT initialized but parameter$out
initialized
function increment(&$out = 4) {
$out++;
}
//No initialization of $in
increment($in);
echo $in; // add up to 1
//NOTE:No effect on referenced variable
case 3: Referenced variable $in
NOT initialized and parameter$out
NOT initialized
function increment(&$out) {
$out++;
}
//No initialization of $in
increment($in);
echo $in; //add up to 1
In my own opinion, case 3, will be a valid solution for the example you describe. Therefore removing the initialization of both $out
and $my_out
should do the work just fine. Something like this:
function dumb_foo($param1, $param2, &$out) {
$out = $param1.'||'.$param2;
return $param1*$param2;
}
dumb_foo(5, 6, $my_out);
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With