diff --git a/src/Php/CompilerBase.php b/src/Php/CompilerBase.php index 2aa627e1..ed5df308 100644 --- a/src/Php/CompilerBase.php +++ b/src/Php/CompilerBase.php @@ -1112,9 +1112,18 @@ class CompilerBase extends \PhpAot\Core\Translator protected function parseBeforeStmtLines(): string { if ($this->context->beforeStmtLines) { - $code = implode(PHP_EOL, $this->context->beforeStmtLines); + $code = implode(PHP_EOL, $this->context->beforeStmtLines); $this->context->beforeStmtLines = []; + return $code . PHP_EOL; + } + return ''; + } + protected function parseAfterStmtLines(): string + { + if ($this->context->afterStmtLines) { + $code = implode(PHP_EOL, $this->context->afterStmtLines); + $this->context->afterStmtLines = []; return $code . PHP_EOL; } return ''; @@ -3526,7 +3535,9 @@ class CompilerBase extends \PhpAot\Core\Translator $initCode .= $this->getIndent() . "if (!{$initState}) { \n"; $this->indentLevel++; $initCode .= $this->getIndent() . "{$initState} = true;\n"; - $initCode .= $this->getIndent() . $this->getStaticVarName($varName) . ' = ' . $this->parseIdentifier($var->default) . ';'; + $initCode .= $this->genLambdaCall(function () use ($var, $varName) { + return $this->getIndent() . $this->getStaticVarName($varName) . ' = ' . $this->parseExpr($var->default) . ';'; + }); $this->indentLevel--; $initCode .= $this->getIndent() . '}'; $list[] = $initCode; diff --git a/src/Php/Generator/ClosureGenerator.php b/src/Php/Generator/ClosureGenerator.php index c9c69628..518da8ed 100644 --- a/src/Php/Generator/ClosureGenerator.php +++ b/src/Php/Generator/ClosureGenerator.php @@ -93,4 +93,24 @@ trait ClosureGenerator return 'php::newClosure(' . $tmpVar . ', { ' . implode(', ', $useVars) . ' })'; } } + + protected function genLambdaCall(callable $cb): string + { + $code = ''; + $oriCtx = $this->context; + + // 使用 lambda 函数来对 static 变量进行赋值 + $this->context = new FunctionContext(); + $code .= '([&](){' . PHP_EOL; + $body = $cb(); + $code .= $this->genLocalVarDecl(); + $code .= $this->parseBeforeStmtLines(); + $code .= $body; + $code .= $this->parseAfterStmtLines(); + $code .= '})();' . PHP_EOL; + + $this->context = $oriCtx; + + return $code; + } } diff --git a/tests/core/lang/bug23384.phpt b/tests/core/lang/bug23384.phpt new file mode 100644 index 00000000..f1246c86 --- /dev/null +++ b/tests/core/lang/bug23384.phpt @@ -0,0 +1,33 @@ +--TEST-- +Bug #23384 (use of class constants in statics) +--FILE-- + 'ten'); + static $arr = array(Foo::HUN => 'ten'); + + print_r($arr); + print_r($arr2); + print_r($x); + } +} + +function main() { + define('TEN', 10); + Foo::test(); + echo Foo::HUN . "\n"; +} +?> +--EXPECT-- +Array +( + [100] => ten +) +Array +( + [10] => ten +) +100100