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 . ')}'; }