I'm trying to convert this C# method into PHP. What does the out in the second parameter mean?
public static bool Foo(string name, out string key)
I'm trying to convert this C# method into PHP. What does the out in the second parameter mean?
public static bool Foo(string name, out string key)
public static function foo($str, &$key)
^
| Pass by reference
Please consider that in C# you must set a value in the calling method when using out
and sadly you can't directly translate that into PHP.
The out
keyword specifies that the parameter must be assigned to by the called method, and the value assigned will be passed back to the calling method. Check out MSDN for more info.
I don't think PHP has an equivalent for the required assignment behavior, but if you are converting the method body, and maintain that behavior internally, you should be able to convert it to a regular pass by reference parameter and maintain the same functionality.
A tiny bit of Googeling brought me to this site: http://www.php.net/manual/en/language.references.pass.php
As you know, a parameter is a copy of a variable.
This means you won't actually change the variable itself.
For example:
<?php
function foo($bar) {
$bar++;
}
$bar = 5; // $bar = 5
foo($bar); // $bar = 6
echo $bar; // $bar = 5
?>
Whilst this piece of code will actually change the given variable, as is uses reference.
<?php
function foo(&$bar) {
$bar++;
}
$bar = 5; // $bar = 5
foo($bar); // $bar = 6
echo $bar; // $bar = 6 now
?>
NOTE: this is not an exact PHP-version of the out-parameter you have in C#