feat(php): 支持 compact 函数中的 'this' 变量

- 添加了对 compact('this') 的支持,允许在类方法中使用 this 变量
- 实现了 'this' 变量的特殊处理逻辑,避免未定义变量错误
- 添加了类上下文检查,防止在类外部使用 compact('this')
- 创建了新的测试文件来验证 compact('this') 在不同场景下的行为
- 更新了函数调用优化器以正确处理 'this' 变量的特殊情况
pull/3/head
韩天峰 2 months ago
parent 989395d7e1
commit 1e6fb4972a
  1. 10
      phpunit/code/compact-this-inside-class.php
  2. 4
      phpunit/code/compact-this-outside-class.php
  3. 18
      phpunit/code/compact_no_this.php
  4. 9
      src/Php/Optimizer/FuncCallOptimizer.php

@ -0,0 +1,10 @@
<?php
function main() {
var_dump(
(new class {
function test() {
return compact('this');
}
})->test()
);
}

@ -0,0 +1,4 @@
<?php
function testCompactThisOutsideClass() {
var_dump(compact('this'));
}

@ -0,0 +1,18 @@
<?php
function main() {
var_dump(
(new class {
function test(){
return (static function(){ return compact('this'); })();
}
})->test()
);
var_dump(compact('this'));
var_dump((function(){ return compact('this'); })());
}

@ -794,14 +794,19 @@ trait FuncCallOptimizer
$this->fatalError($expr, 'The argument of compact function can only be literal string'); $this->fatalError($expr, 'The argument of compact function can only be literal string');
} }
$var = $arg->value->value; $var = $arg->value->value;
if (!$this->hasVar($var)) { if (!$this->hasVar($var) && $var !== 'this') {
$this->errorUndefinedVariable($var); $this->fatalError($arg->value, "Undefined variable `{$var}` in compact()");
} }
if ($this->isSuperGlobal($var)) { if ($this->isSuperGlobal($var)) {
$this->fatalError($expr, 'Cannot use super global variable `' . $var . '` in compact function'); $this->fatalError($expr, 'Cannot use super global variable `' . $var . '` in compact function');
} }
$key = $this->getLiteralString($var); $key = $this->getLiteralString($var);
if ($var === 'this') {
if (empty($this->class)) {
$this->fatalError($expr, 'Cannot use compact("this") outside of class method');
}
}
$cVar = $this->escapeVarName($var); $cVar = $this->escapeVarName($var);
$list[] = '{' . $key . '.str(), php::Var(' . $cVar . ')}'; $list[] = '{' . $key . '.str(), php::Var(' . $cVar . ')}';
} }

Loading…
Cancel
Save