Call to a member function on a non-object error in Symfony2

There is this error that I was having trouble with in my project. It was an implementation of ZeroMQ and RatchetPHP on Symfony2. The web socket service I did was keep on crashing caused by this error

Error: Call to a member function broadcast() on a nonobject

The command it was executing was $topic->broadcast($msg). I tried doing a try catch but the error still occurs. After some reading, seems that the issue was on the variable $topic. Next thing I did was to check of what type was the variable $topic by:

echo get_class($topic) and it returned ‘Ratchet\Wamp\Topic‘.

After determining it’s correct type, I added a condition to check before doing the broadcast if it was of the correct object type:

if(is_a($topic, ‘Ratchet\Wamp\Topic’)) { $topic->broadcast($msg); }

Now, the service doesn’t crash anymore. Seems that at times it was returning a NULL object class when the $msg was actually empty.