Archive for the ‘ Symfony 1.x ’ Category

Author : beriba | 09/02/2012

In big projects, where many developers can put their fingers over the code sometimes unpredictable things can happen. It’s obvious. Especially when the project is written in PHP. Many classes, even more methods – big mess. In such projects it is not easy (if even possible) to know every name of every class. Sometimes PHP interpreter will tell you that:

Fatal error: Cannot redeclare class MyClass in /tmp/MyClass.php on line 4

It can be the result of this code:

class myClass {

class myClass {

And you can say: „Yeah, right. Who can write such stupid code”. I’ll say – you never know. But this is just a sample when you can expect such error. If you know how to trigger an error on purpose, you’re half way to avoid triggering it unexpectedly. Of course it gets harder when duplicated class names are in two different, not related files. The only solution for that is to rename one of the classes. If you don’t know how to find them, I’ll give you a solution in the end of this post.

Almost the same error could get a little bit tricky to resolve in some conditions. When you are using some kind of autoloader (for example Symfony Framework) and you declare classes of the same name in two different files it is very likely that you won’t get above error. Why? It’s because autoloader will load the first class and then replace it with second. When you’ll try to invoke a method on object (which you think is an instance of the first class) you’ll get an error:

Fatal error: Call to undefined method MyClass::doSomething() in 
/tmp/MyClass.php on line 6

But you have your class just in front of your face, the method exists and you think „what the…”. There could be more than one reason of this error. First is explained above. The second – code you’ve written is just in memory of your editor or IDE and was not saved in file. Yes, this could sometimes happen – espacially when you work on remote project. Just open the file in another editor and find out what’s inside. If it’s the first reason we need to check which class is actually loaded. For that you can use static method:

public static function getPathToObject($object, $method = '__construct')
    $object = new ReflectionObject($object);
    $method = $object->getMethod($method);
    $declaringClass = $method->getDeclaringClass();
    $filepath = $declaringClass->getFilename();
    return $filepath;

It uses reflection to find path to loaded object. If the given path is different from the file you’re looking at then you just need to rename one of the classes. If the paths are the same then… you can ask me in the comments and I’ll try to help 🙂