searchfe / searchfe/ts2php

函数中引用传参

Open
#77 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

help wanted
Dominant language
TypeScript
Stars
98
Forks
20
Avg merge
5m
Merged PRs (30d)
3

Description

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"];

问题更加复杂了

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by tracing how the transpiler converts function parameters, return values, and calls into PHP, using the issue's TypeScript and PHP examples as reproduction cases. Investigate both referenced arguments and returned references, including calls with array literals. Done means the intended reference semantics are defined and the examples behave consistently without invalid PHP.

Written by the indexing model from the issue text.

Assessment

Tech stack
php, typescript
Domain
compilers
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.