A quick 1-minute solution to resolve “Cannot declare class Attribute, because the name is already in use” or similar PHP error messages.

I was trying to create a PHP class to model after my Attributes database table, when I encountered this error that says I can not declare this class, because it is already in use. Turns out PHP 8 started using Attribute as a keyword, so all I had to do was rename the class and it started working. PHP 8 Attribute reference: https://www.php.net/manual/en/language.attributes.overview.php

The more common case for this is accidentally including the class multiple times. To quickly demonstrate this, I’m going to include the Attr class in my Product.php file, then I’ll include the Product and Attribute class in my Test file. So essentially, I’ve included the Attr file twice and it produces the same error. The way to solve this is to use require_once or include_once, so that when PHP encounters the same file, it doesn’t try to include it again.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top