tags:

views:

63

answers:

3

From the demo below you can probably see what I am trying to do, the construct method works but the test method does not work, gives error Fatal error: Call to a member function get() on a non-object

Can someone show me how to make something like this work?

<?PHP
//user.class.php file
class User
{
    public $pic_url;

    function __construct($session)
    {
     if($session->get('auto_id') != ''){
      $this->pic_url = $session->get('pic_url');
     }else{
      return false;
     }
    }

    function test($session)
    {
     return $this->pic_url = $session->get('pic_url');
    }
}

$user = new user($session);

//this works
echo $user->pic_url;

//this one does not work
echo $user->test();
?>
+2  A: 

You're not supplying the $session to the function.

Sbm007
He's right, but I thought I'd explain the error message a little more. It states that you are calling `get` on a "non-object" - hence, `$session` is a non-object. From this you can deduce that `$session` isn't being set correctly.
Samir Talwar
A: 

Try this :

<?php
//user.class.php file
class User
{
    public $pic_url;

    public function __construct($session)
    {
        if($session->get('auto_id') != ''){
                $this->pic_url = $session->get('pic_url');
        } else {
                return false;
        }
    }

    public function test($session)
    {
        if($this->pic_url == $session->get('pic_url')) {
            return $this->pic_url;
        } else {
            return 'test failed';
        }
    }
}

$user = new User($session);

//this works
echo $user->pic_url;

//this one does not work
echo $user->test();
Kevin Campion
+1  A: 

//this one does not work echo $user->test();

Calling a function here without an argument should throw a warning

Warning: Missing argument 1 for test(), called in ....

and because you are trying to access a function of that object which don't pass in test() call its throwing a Fatal error as well.

Just pass the $session argument to test() as well.

OR you can try ..

class User
{
    public $pic_url;
    private $class_session;

 public function __construct($session)
 {
     $this->class_session = $session;
     ... other code
 }
 function test()
    {
        return $this->pic_url = $this->class_session->get('pic_url');
    }
}

$user = new user($session);
echo $user->pic_url;
echo $user->test();
Wbdvlpr