【发布时间】:2022-09-23 01:40:03
【问题描述】:
如果我有两个函数,它们的参数都包含对字符串的引用。一个函数将调用另一个函数,但两个函数都可以设置引用变量的值。
目前,下面的代码会将变量保留为NULL,而不是更新变量。我确定正在设置原因,因为我可以在设置原因的位置断点(甚至在当前范围内输出原因)。
function function_a(string $path, ?string &$reason = null): ?string {
// Set to false for example purposes
$checkIsValid = false;
if(!$checkIsValid) {
$reason = \'Reason why it is invalid\';
return null;
}
return function_b($path, $reason);
}
function function_b(string $path, ?string &$reason = null): ?string {
$anotherValidCheck = false;
if($anotherValidCheck) {
$reason = \'Another reason why it is invalid\';
return null;
}
return \'Some value\';
}
还有一个核心 PHP 函数,它使用与我试图实现的功能相似的功能 (output argument in the exec function)。另一个例子是 .NET 中的 out 关键字。我猜测,因为 PHP 引用与您的典型引用不太一样,所以这不起作用?
-
我不明白,这似乎按预期工作。如果我实例化一个字符串变量并将其作为
function_a的第二个参数传递,它的值在我调用该函数的范围内确实更改为\'Reason why it is invalid\'。 -
嗯,您似乎是对的,在沙箱中它可以工作,但在我的本地却没有。我一定错过了一些愚蠢的事情。
标签: php function pass-by-reference