Notice! This post is more than a year old. It may be outdated.
I am fairly new to PHP and Yii. Lately i struggled with a “cannot redeclare class” error. Here’s a brief overview of my setup. I’m using Yii’s Active Record and I have 2 models (
ChildModel) with a one-to-many relation. Both model classes have namespaces. In addition, I’m using Codeception for testing. Upon running unit tests, i received the following error:
PHP Fatal error: Cannot redeclare class application\models\ChildModel in /var/www/demo/app/models/ChildModel.php on line 49
This occurred while i was trying to save
ParentModel to database. Doing the same process while using the web application did not cause this error. After hours of debugging, reading Yii’s source code and googling, I finally found a solution. The culprit was the usage of namespaces in model classes. Here’s how I defined the relations between the two model classes:
As mentioned previously, the problem was the usage of namespaces, or the mis-usage of namespaces, to be more precise. In the relations array I should have used the model’s fully qualified name (namespace + class name). The following is the working code:
Hopefully this post was helpful for somebody.