Search code examples
symfony1doctrine-ormphp

Calling a member function on a non object - php


Here is my code of SessionManager.php:

private function generateAuthToken($user)
{
    $bits = '';

    $fp = @fopen('/dev/urandom', 'rb');
    if ($fp !== false) {
        $bits .= @fread($fp, 128);
        @fclose($fp);
    }

    return sha1($bits . time() . microtime() . $user->getUsername());
}

I'm getting this error:

Fatal error: Call to a member function getUsername() on a non-object in /home/shwetanka/src/Practo/PvrBundle/Manager/SessionManager.php on line 49

When I'm doing var_dump($user); right before the problem line I'm getting the full user object printed. I'm unable to understand the reason of this error. The function is present in the class User. Even if I try to call any other function of the class even then I get the same error for that function. I'm new to php and having hard time debugging this problem.

Also $user is object of User entity. I'm using symfony2 and this object is returned to me by using this:

$ur = $this->getDoctrine()->getRepository('PractoPvrBundle:User');
$user = $ur->findBy(array('email' => $email));

Solution

  • Sometimes in the implicitly-convert-to-string context, PHP does not do well with method calls... I'm not sure why. Try this:

    $username = $user->getUsername();
    return sha1($bits . time() . microtime() . $username);
    

    edit:

    Also, I suspect that you are actually dealing with an array instead of an object. the line:

    $user = $ur->findBy(array('email' => $email));
    

    is probably intended to return many results. Use current() to get the first one:

    $user = current($ur->findBy(array('email' => $email)));