Use Deprecated Attribute in PHP 8.4

Use Deprecated Attribute in PHP 8.4

Since PHP 8.4, we can use the #[Deprecated] attribute to mark functionality as deprecated, providing a clear indication to developers that the feature should no longer be used and may be removed in future versions.

Before PHP 8.4, the @deprecated annotation could be used. Static analyzers and IDEs could interpret these doc blocks, but PHP itself did not take any action based on it.

NewsletterManager.php

<?php

class NewsletterManager
{
    /**
     * @deprecated since 2.0, use NewsletterManager::send() instead
     */
    public function sendMessage(): void
    {
    }

    public function send(): void
    {
    }
}
<?php

require_once 'NewsletterManager.php';

$manager = new NewsletterManager();
$manager->sendMessage(); // There is no output that the method is deprecated.

The #[Deprecated] attribute can be used to mark functions, methods, and class constants as deprecated. The behavior of functionality marked with this attribute aligns with PHP's existing deprecation mechanism, with the only difference being that the error code emitted is E_USER_DEPRECATED instead of E_DEPRECATED.

The #[Deprecated] attribute accepts two optional parameters: a message explaining the reason for the deprecation and a string specifying when the functionality was deprecated.

NewsletterManager.php

<?php

class NewsletterManager
{
    #[Deprecated('use NewsletterManager::send() instead', '2.0')]
    public function sendMessage(): void
    {
    }

    public function send(): void
    {
    }
}
<?php

require_once 'NewsletterManager.php';

$manager = new NewsletterManager();
$manager->sendMessage();

The code outputs a deprecation message:

Deprecated: Method NewsletterManager::sendMessage() is deprecated since 2.0, use NewsletterManager::send() instead in ...

Leave a Comment

Cancel reply

Your email address will not be published.