开发者

Automatic deprecated warnings for PHP methods with @deprecated annotation

What are possibilities to implement helper that will raise error log with level E_DEPRECATED (E_USER_DEPRECATED in fact) when class method with annotation @deprecated is called?

For example for the code

/**
 * @deprecated
 */
public function main()
{}

when calling the method $obj->main() the deprecated warning would be 开发者_如何学编程raised.

And yes, I know I could add a warning using code line trigger_error().


In short: Put trigger_error() at the beginning of the method.

Long: You need to reflect the class, retrieve the DocComment, parse it and extract the @deprecated-tag. The problem is, that you must do this on every method call, and even if it there exists an easy way to catch every call, it would be a huge overhead.


If you are still interested in an answer:

$trace = debug_backtrace();
$trace = $trace[0];
Helper::logToFile('called deprecated method '.__ FUNCTION __.' on line '.$trace['line'].' in file '.$trace['file'], 'deprecated');

Where the log to file method could look like:

$text .= "\n";
$file = fopen('log/deprecated', 'a+');
fputs($file, $text, strlen($text));
fclose($file);


There is an RFC for it, but under discussion: #[Deprecated] Attribute. If accepted, you will be able to do this, for example:

#[Deprecated("use split() instead")]
function explode() {}

When you call it, it will emit a deprecation notice, like so:

Deprecated: Function explode() is deprecated, use split() instead

Maybe we could get this in PHP 8.2? I hope so!


  1. may be own file parser helps you...
  2. deprecated mean that in next version this function will be removed from code... in this case you do not need to think about E_DEPRECATED


Addendum might help, it adds annotations to PHP.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜