fix(php): 解决方法调用时的类型检查和反射问题

- 在方法调用前添加变量类型检查,防止对非对象类型调用方法
- 修复反射中获取方法返回类型的逻辑,改进变量命名避免冲突
- 添加对字符串类型参数调用对象方法的错误检测和提示
pull/1/head
韩天峰 4 months ago
parent 2d0baeaea9
commit eba8964d34
  1. 15
      examples/error/call-str-method.php
  2. 4
      src/Php/CompilerBase.php
  3. 10
      src/Php/Reflection.php

@ -0,0 +1,15 @@
<?php
function bar(): stdClass
{
return new stdClass();
}
function foo(string $o)
{
$o2 = bar();
$o2->call();
}
function main()
{
foo("hello");
}

@ -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));

@ -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;
}
}

Loading…
Cancel
Save