Calling Non-Static Class Methods Statically Produces Fatal Error in PHP 8.0

Calling Non-Static Class Methods Statically Produces Fatal Error in PHP 8.0

A non-static method is a method that belongs to an instance of a class. In all PHP 7 versions, calling non-static methods statically is deprecated and emits a warning (E_DEPRECATED).

Let's say we have a User class with one non-static method:

User.php

<?php

class User
{
    public function saySomething(): void
    {
        echo 'Hello';
    }
}

A saySomething method is invoked statically without creating an instance of a class.

<?php

require_once 'User.php';

User::saySomething();

In PHP 7, calling the saySomething method statically produces a warning and prints Hello message.

Deprecated: Non-static method User::saySomething() should not be called statically in main.php on line 5
Hello

Since PHP 8.0, no longer allows calling non-static class methods statically. It produces a fatal error.

PHP Fatal error:  Uncaught Error: Non-static method User::saySomething() cannot be called statically in main.php:5

Leave a Comment

Cancel reply

Your email address will not be published.