Skip to content
Advertisement

Why is PHP saying my class name is already being used when It’s the first time I’ve declared it

Apologies for the long code, it’s 4 files but I have no choice since the problem can be any where. Thankfully I’ve found the solution I’m just trying to figure out why this had happened in the first place, so that will probably cut down the time significantly.

classes/Cart.php

JavaScript

classes/CartItem.php

JavaScript

classes/Product.php

JavaScript

./index.php

JavaScript

So if I were to run the code on index.html it gave me this error

JavaScript

which is weird because I’ve never declared it anywhere else.

now the solution for this it to shuffle the required_once from this:

JavaScript

to this:

JavaScript

and it worked perfectly! any idea of why this had happened?

Advertisement

Answer

I think this was caused by me using require instead of require_once in Cart so if class Product comes first then the class CartItem will be redeclared since class Cart did not check if CartItem was already declared in the code.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement