0

是否可以在析构函数中获取被调用的函数名称?

class My_class {

    function my_func() {
        echo 'Hii';
    }

    function your_func() {
        echo 'Hii';
    }

    function __destruct() {
        echo $the_called_func_name;
    }
}


$bar = new my_class();
$bar->my_func();

是否有可能my_func在析构函数中获得名称''?

如果我们使用

echo __FUNCTION__;

它会给

__destruct

我想要

my_func
4

3 回答 3

2

对的,这是可能的。由于my_func是动态的,您可以使用函数重载(又名魔术方法)__call()

class My_Class
{

   private $methods = array(); 


   public function __call($method, array $args)
   {
      array_push($this->methods, $method);
   }

   public function getMethods()
   {
      return $this->methods;
   }

   public function __destruct()
   {
      // Off course, you should improve this 
      print_r($this->getMethods());
   }
}

// Usage:

$foo = new My_Class();
$foo->my_func(); // Output Array(0 => 'my_func')
于 2013-03-23T10:00:55.450 回答
1

它仅用于记录已访问的功能。而不是在每个函数中调用 log 函数。

如果不向方法中添加代码或使用单独的工具进行调试和分析,这是不容易实现的。

请注意,建议的解决方案__call不适用于现有的公共方法,最终它会变得比仅添加log(__METHOD__)到每个方法更复杂。

您正在寻找的基本上是面向方面的编程(AOP),它在 PHP 中并没有得到很好的支持。Flow3 框架使用注解和反射来动态添加方面。他们的日志记录示例完美地说明了您的用例:

namespace Example\MyPackage;

/**
 * A logging aspect
 *
 * @Flow\Aspect
 */
class LoggingAspect {

        /**
         * @var \TYPO3\Flow\Log\LoggerInterface A logger implementation
         */
        protected $logger;

        /**
         * For logging we need a logger, which we will get injected automatically by
         * the Object Manager
         *
         * @param \TYPO3\Flow\Log\SystemLoggerInterface $logger The System Logger
         * @return void
         */
        public function injectSystemLogger(\TYPO3\Flow\Log\SystemLoggerInterface ⏎
                $systemLogger) {
                $this->logger = $systemLogger;
        }

        /**
         * Before advice, logs all access to public methods of our package
         *
         * @param  \TYPO3\Flow\AOP\JoinPointInterface $joinPoint: The current join point
         * @return void
         * @Flow\Before("method(public Example\MyPackage\.*->.*())")
         */
        public function logMethodExecution(\TYPO3\Flow\AOP\JoinPointInterface $joinPoint) {
                $logMessage = 'The method ' . $joinPoint->getMethodName() . ' in class ' .
                        $joinPoint->getClassName() . ' has been called.';
                $this->logger->log($logMessage);
        }
}

重要的一行是这样的:

@Flow\Before("method(public Example\MyPackage\.*->.*())")

它告诉框架在命名空间logMethodExecution的任何类中的任何方法调用之前调用Example\MyPackage

因此,使用Flow3您可以做到。但是在没有 AOP 框架的情况下自己实现类似的行为必然会失败。

于 2013-03-23T14:21:16.880 回答
0

是的,

class My_class {

    function my_func() {
        echo 'Hii';
    }

    function your_func() {
        echo 'Hii';
    }

    function __destruct() {
        self::my_func();
        // my_func called
    }
}


$bar = new my_class();
$bar->my_func();

如果您的意思是函数名称,请__call用于对象函数和__callStatic静态函数。

于 2013-03-23T09:54:47.923 回答