I’m programming a website with PHP using Symfony2.
I defined a class MainContent in file MainController.php
And I had to use this class in other controller file named SecurityController.php
Although both of these classes are defined in the same namespace, it gave the error:
Class 'MainContent' not found...
So I tried to define the class again in SecurityController.php but result is:
Cannot redeclare class 'MainContent...'
I don’t understand, it is either declared or not.
In fact I’m a C# programmer and maybe I’m confused because of some differences between these languages.
Symfony uses so-called autoloading. Since your class is not defined in it’s own file, following the rules for auto-loading, it cannot be loaded, hence the class not found. But if you define the class, then script is processed successfully, other file that defines the same class is included, and the collision (cannot redeclare class) is generated.
The possible solutions are:
Whenever you are declaring the class, use
if(!class_exists('ClassName')) {class ClassName {}
}