Reputation: 48963
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();
?>
Upvotes: 0
Views: 97
Reputation: 10806
//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();
Upvotes: 2
Reputation: 2339
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();
Upvotes: 0