Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

函数中引用传参 #77

Open
meixg opened this issue Nov 6, 2019 · 0 comments
Open

函数中引用传参 #77

meixg opened this issue Nov 6, 2019 · 0 comments
Labels
help wanted Extra attention is needed

Comments

@meixg
Copy link
Member

meixg commented Nov 6, 2019

TS 中函数的参数默认为引用传递:

let a = [];
function aaa(b) {
    b[0] = 1;
}
aaa(a);
console.log(a[0]); // 1

但 PHP 中默认为值传递:

$a = array();
function aaa($b) {
    $b['0'] = 1;
}
aaa($a);
echo $a['0']; // undefined

如果在转换函数定义时,参数部分增加 &,可以解决上述问题。

$a = array();
function aaa(&$b) {
    $b['0'] = 1;
}
aaa($a);
echo $a['0']; // 1

但函数参数为字面量形式时会报错,目前找到好的解决方法:

function aaa(&$b) {
    $b['0'] = 1;
}
aaa(array()); // Error

此外,如果函数返回值也会有引用传递问题,例如:

let a = [];
function bbb(c) {
    return c;
}
let b = bbb(a);
b[0] = 1;
console.log(a[0]); // 1

需要翻译成如下 PHP 代码才能有同样效果:

$a = array();
function &bbb(&$c) {
    return $c;
}
$b = &bbb($a);
$b["0"] = 1;

echo $a["0"];

问题更加复杂了

@meixg meixg added the help wanted Extra attention is needed label Nov 6, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
help wanted Extra attention is needed
Projects
None yet
Development

No branches or pull requests

1 participant