The PHP Language Specification说:
A variable is an expression that can in principle be used as an lvalue
和
The value of a function call is a modifiable lvalue only if the function returns a modifiable value byRef.
和来自 zend_language_parser.y 的语法
expr:
variable T_CONCAT_EQUAL expr
callable_variable:
simple_variable
{ $$ = zend_ast_create(ZEND_AST_VAR, $1); }
| dereferencable '[' optional_expr ']'
{ $$ = zend_ast_create(ZEND_AST_DIM, $1, $3); }
| constant '[' optional_expr ']'
{ $$ = zend_ast_create(ZEND_AST_DIM, $1, $3); }
| dereferencable '{' expr '}'
{ $$ = zend_ast_create_ex(ZEND_AST_DIM, ZEND_DIM_ALTERNATIVE_SYNTAX, $1, $3); }
| dereferencable T_OBJECT_OPERATOR property_name argument_list
{ $$ = zend_ast_create(ZEND_AST_METHOD_CALL, $1, $3, $4); }
| function_call { $$ = $1; }
;
variable:
callable_variable
{ $$ = $1; }
| static_member
{ $$ = $1; }
| dereferencable T_OBJECT_OPERATOR property_name
{ $$ = zend_ast_create(ZEND_AST_PROP, $1, $3); }
;
那么为什么我不能在 PHP 7.3 中做到这一点呢?
<?php
$a = 'HELLO';
function &foo() {
global $a;
return $a;
}
foo() .= ' WORLD';
echo $a;
PHP Fatal error: Can't use function return value in write context in ...
从这个问题继续,引用上面的语法:
什么时候可以在简单/复合赋值表达式的左侧进行函数调用?
最佳答案
虽然您可以从函数返回引用,但不能直接写入该引用。
您必须先分配引用。
$a = 'HELLO';
function &foo() {
global $a;
return $a;
}
$b =& foo();
$b .= ' WORLD';
echo $a;
关于php - 在 PHP 中写入函数的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58446612/