How to deprecate a function in PHP? How to deprecate a function in PHP? php php

How to deprecate a function in PHP?


trigger_error()

function my_deprecated_function() {    trigger_error("Deprecated function called.", E_USER_NOTICE);    // do stuff.}


Generally speaking you can flag a method as deprecated to give your users warnings about code that will not work in future versions. I think the best way is to use trigger_error along with some phpdoc.

/** * @deprecated * * @return $this */public function oldMethod(){    trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);    return $this;}

The @deprecated phpdoc is important because many IDEs like PHPStorm recognise it and strike the method name if you try to use it, so you notice that is deprecated before actually running your code.

It will look more or less like this:

jetbrains deprecated strikethrough

Beside the phpdoc you can make sure the user gets a warning by triggering the right error at runtime. Just make sure you use the right constant (i.e. E_USER_DEPRECATED).

E_DEPRECATED is instead used internally by PHP thus you should not be using it. More information here.


If I understand correct, you want to trigger an error when a built-in PHP function is used? In that case, take a look at the Override Function function.