PHP-ReflectionFunction-函数Test :: test_function()不存在

时间:2018-11-06 08:47:06

标签: php

我可以在课程外使用OfficeProperties,但在课程内会遇到异常。

  

致命错误:未捕获ReflectionException:函数Test :: test_function()在test.php中不存在。

RefexionFunction

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您的错误:

  

致命错误:未捕获ReflectionException:函数Test :: test_function()在test.php中不存在。

没有按您期望的那样引用函数名称。

ReflectionClass文档说:

  

ReflectionClass类报告有关类的信息。   
  参考:https://secure.php.net/manual/en/class.reflectionclass.php

您想使用该类中可用的方法的组合来获取有关传递的方法的信息,如下所示:

public function parameters($class, $fnc)
{
    $f = new ReflectionClass($class);

    if ($f->hasMethod($fnc)) {
        return 'howdy folks';
    } else {
        return 'not so howdy folks';
    }
}

在检查功能是否存在之前,您首先通过。然后,您可以使用内置函数hasMethod检查该函数是否存在。然后,您可以使用以下参数函数:

public function testFunction()
{
    return $this->helper->parameters(__CLASS__, __FUNCTION__);
}

所有代码看起来像这样:

<?php
    ini_set('display_startup_errors', 1);
    ini_set('display_errors', 1);
    error_reporting(-1);

    class paramsHelper
    {
        public function parameters($class, $fnc)
        {
            $f = new ReflectionClass($class);
            $f->getMethod($fnc);

            if ($f->hasMethod($fnc)) {
                return 'howdy folks';
            } else {
                return 'not so howdy folks';
            }

            return $f;
        }
    }

    class Test
    {
        protected $helper;

        public function __construct($helper)
        {
            $this->helper = $helper;
        }

        public function testFunction()
        {
            return $this->helper->parameters(__CLASS__, __FUNCTION__);
        }
    }

    $test = new Test(new paramsHelper());

    echo '<pre>';
    print_r($test->testFunction());
    echo '</pre>';

您的另一个问题是__METHOD__实际上返回这样的字符串:Test::testFunction而不是testFunction-因此我改用__FUNCTION__

编辑:

要获取传递的方法的参数,请将您的parameters方法更改为:

class paramsHelper
{
    public function getMethodParameters($class, $fnc)
    {
        $f = new ReflectionMethod($class, $fnc);

        echo '<pre>';
        print_r($f->getParameters());
        echo '</pre>';
    }
}

此方法使用ReflectionMethod代替ReflectionClass-这更符合您的预期用途。

ref:https://secure.php.net/manual/en/class.reflectionmethod.php

使用:

class paramsHelper
{
    public function getMethodParameters($class, $fnc)
    {
        $f = new ReflectionMethod($class, $fnc);

        echo '<pre>';
        print_r($f->getParameters());
        echo '</pre>';
    }
}

class Test
{
    protected $helper;

    public function __construct($helper)
    {
        $this->helper = $helper;
    }

    public function testFunction($a = '', $b = 1, $c = 3)
    {
        return $this->helper->parameters(__CLASS__, __FUNCTION__);
    }
}

$test = new Test(new paramsHelper());

echo '<pre>';
print_r($test->testFunction());
echo '</pre>';