From 1e6fb4972a8ce6145a5919d24628cc90a585bf0d Mon Sep 17 00:00:00 2001 From: tianfenghan Date: Thu, 18 Jun 2026 18:35:18 +0800 Subject: [PATCH] =?UTF-8?q?feat(php):=20=E6=94=AF=E6=8C=81=20compact=20?= =?UTF-8?q?=E5=87=BD=E6=95=B0=E4=B8=AD=E7=9A=84=20'this'=20=E5=8F=98?= =?UTF-8?q?=E9=87=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 添加了对 compact('this') 的支持,允许在类方法中使用 this 变量 - 实现了 'this' 变量的特殊处理逻辑,避免未定义变量错误 - 添加了类上下文检查,防止在类外部使用 compact('this') - 创建了新的测试文件来验证 compact('this') 在不同场景下的行为 - 更新了函数调用优化器以正确处理 'this' 变量的特殊情况 --- phpunit/code/compact-this-inside-class.php | 10 ++++++++++ phpunit/code/compact-this-outside-class.php | 4 ++++ phpunit/code/compact_no_this.php | 18 ++++++++++++++++++ src/Php/Optimizer/FuncCallOptimizer.php | 9 +++++++-- 4 files changed, 39 insertions(+), 2 deletions(-) create mode 100644 phpunit/code/compact-this-inside-class.php create mode 100644 phpunit/code/compact-this-outside-class.php create mode 100644 phpunit/code/compact_no_this.php diff --git a/phpunit/code/compact-this-inside-class.php b/phpunit/code/compact-this-inside-class.php new file mode 100644 index 00000000..72d30c5e --- /dev/null +++ b/phpunit/code/compact-this-inside-class.php @@ -0,0 +1,10 @@ +test() + ); +} diff --git a/phpunit/code/compact-this-outside-class.php b/phpunit/code/compact-this-outside-class.php new file mode 100644 index 00000000..9c366c67 --- /dev/null +++ b/phpunit/code/compact-this-outside-class.php @@ -0,0 +1,4 @@ +test() +); + +var_dump(compact('this')); + +var_dump((function(){ return compact('this'); })()); + + +} diff --git a/src/Php/Optimizer/FuncCallOptimizer.php b/src/Php/Optimizer/FuncCallOptimizer.php index 5cdfbf11..b13baa84 100644 --- a/src/Php/Optimizer/FuncCallOptimizer.php +++ b/src/Php/Optimizer/FuncCallOptimizer.php @@ -794,14 +794,19 @@ trait FuncCallOptimizer $this->fatalError($expr, 'The argument of compact function can only be literal string'); } $var = $arg->value->value; - if (!$this->hasVar($var)) { - $this->errorUndefinedVariable($var); + if (!$this->hasVar($var) && $var !== 'this') { + $this->fatalError($arg->value, "Undefined variable `{$var}` in compact()"); } if ($this->isSuperGlobal($var)) { $this->fatalError($expr, 'Cannot use super global variable `' . $var . '` in compact function'); } $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); $list[] = '{' . $key . '.str(), php::Var(' . $cVar . ')}'; }