Ahbiggie
Ahbiggie

Reputation: 45

PHP Fatal error: Cannot use ::class with dynamic class name

I uploaded a website to a live server with this code

class Model extends Database
{
    public $errors = array();

    public function __construct()
    {
        // code...
        if(!property_exists($this, 'table'))
        {
            $this->table = strtolower($this::class) . "s";
            
        }
    }
}

but I keep getting this error: PHP fatal error: cannot use ::class with dynamic class name I've tried using the get_class() function but I don't think I'm using it properly, cause it takes me the controller not found page in the else block

    public function __construct()
    {
        // code...
        $URL = $this->getURL();
        if(file_exists("../private/controllers/".$URL[0].".php"))
        {
            $this->controller = ucfirst($URL[0]);
            unset($URL[0]);
        }else
        {
            echo"<center><h1>controller not found: " . $URL[0] . "</h1></center>";
            die;
        }

here's how I've been using it

if  (!property_exists($this, 'table'))
        {
            $this->table = strtolower(get_class($this)) . "s";

        }

Upvotes: 4

Views: 5658

Answers (2)

Leo
Leo

Reputation: 1505

You can replace it with get_class()

It seems that some versions of php don't support $this::class. It was implemented in php version 5.5. but I am using php version 7.4.12 and it throws the error.

Upvotes: 1

Martin Zeitler
Martin Zeitler

Reputation: 76689

$this::class is non-sense, because you cannot use the scope resolution operator on an object's instance. Instead use the default predefined constant __CLASS__ for the current class. Or function get_class(object $object = ?): string to get the class from any object's instance.

Upvotes: 3

Related Questions