From eba8964d34e236a7963f46d62abd55163c41743d Mon Sep 17 00:00:00 2001 From: tianfenghan Date: Mon, 27 Apr 2026 13:25:12 +0800 Subject: [PATCH] =?UTF-8?q?fix(php):=20=E8=A7=A3=E5=86=B3=E6=96=B9?= =?UTF-8?q?=E6=B3=95=E8=B0=83=E7=94=A8=E6=97=B6=E7=9A=84=E7=B1=BB=E5=9E=8B?= =?UTF-8?q?=E6=A3=80=E6=9F=A5=E5=92=8C=E5=8F=8D=E5=B0=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 在方法调用前添加变量类型检查,防止对非对象类型调用方法 - 修复反射中获取方法返回类型的逻辑,改进变量命名避免冲突 - 添加对字符串类型参数调用对象方法的错误检测和提示 --- examples/error/call-str-method.php | 15 +++++++++++++++ src/Php/CompilerBase.php | 4 ++++ src/Php/Reflection.php | 10 +++++----- 3 files changed, 24 insertions(+), 5 deletions(-) create mode 100644 examples/error/call-str-method.php diff --git a/examples/error/call-str-method.php b/examples/error/call-str-method.php new file mode 100644 index 00000000..c39b9b02 --- /dev/null +++ b/examples/error/call-str-method.php @@ -0,0 +1,15 @@ +call(); +} + +function main() +{ + foo("hello"); +} diff --git a/src/Php/CompilerBase.php b/src/Php/CompilerBase.php index cd9012e5..c6611f48 100644 --- a/src/Php/CompilerBase.php +++ b/src/Php/CompilerBase.php @@ -4137,6 +4137,10 @@ class CompilerBase extends \PhpAot\Core\Translator // 可转为原生调用的 MethodCall if ($this->isVarExpr($expr->var) and $this->isNamedMethod($expr->name)) { + $type = $this->getVarType($object); + if (!$this->checkArgType($type, self::TYPE_OBJECT)) { + $this->fatalError($expr, 'Cannot call method `' . $expr->name->toString() . '()` on variable of type ' . $type); + } $this->context->beforeStmtLines[] = '// Method Call: ' . $object . '->' . $this->parseIdentifier($expr->name) . '()'; try { $nativeFunc = $this->findNativeMethod($expr, $object, $this->parseIdentifier($expr->name)); diff --git a/src/Php/Reflection.php b/src/Php/Reflection.php index e2b1a3a7..e05dd2c0 100644 --- a/src/Php/Reflection.php +++ b/src/Php/Reflection.php @@ -177,14 +177,14 @@ class Reflection public static function getMethodReturnType(string $class, string $method): ?string { - $class = self::getClass($class); - if (!$class) { + $classRef = self::getClass($class); + if (!$classRef) { return null; } - if (!$class->hasMethod($method)) { + if (!$classRef->hasMethod($method)) { return null; } - $method = $class->getMethod($method); - return $method->getReturnType() ? $method->getReturnType()->getName() : null; + $methodDef = $classRef->getMethod($method); + return $methodDef->getReturnType() ? $methodDef->getReturnType()->getName() : null; } }