PHP函数中如何更新引用类型参数?
PHP 嵌套函数中引用参数无法更新的问题解决
我有两个均包含字符串引用参数的函数,一个函数会调用另一个,且两者都需要具备修改引用变量值的能力。目前下方代码中的变量始终为NULL,无法被更新,但我能确认代码中已对reason进行赋值(可在当前作用域输出该值)。
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核心函数exec的输出参数也采用类似功能,.NET中的out关键字亦是如此。我猜测因PHP引用与常规引用不同,导致该功能无法实现?
问题出在函数调用时的引用传递方式,而非PHP引用机制本身的问题。
在function_a中调用function_b时,你直接传递了$reason变量,但没有显式声明这是一个引用传递。尽管function_a的$reason是引用参数,但在传递给function_b时,默认是值传递——这意味着function_b会创建一个$reason的副本,修改副本不会影响原始的引用变量。
修复方案
修改function_a中调用function_b的代码,在$reason前添加&,明确传递引用:
return function_b($path, &$reason);
修改后的完整代码:
function function_a(string $path, ?string &$reason = null): ?string { $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'; }
验证测试
调用函数时,外部变量就能正确被修改了:
$reason = null; $result = function_a('/test/path', $reason); echo $reason; // 输出 "Reason why it is invalid"
PHP的引用机制和.NET的out关键字逻辑类似,只要确保在函数调用时显式传递引用,就能实现跨函数修改外部变量的效果。exec函数也是通过这种引用传递的方式来返回输出结果的。
内容的提问来源于stack exchange,提问作者Sutton
相关产品推荐
相关产品推荐

