...

View Full Version : Accessing object fields



nerhael
04-01-2004, 04:36 PM
Okay, here's the deal, I store a usersession type object in the $_SESSION var.

Currently, to use it, I use


$userId = $_SESSION['user']->userId;
What I wanted to do was write a simply function to return that object.


function getUser() {
return $_SESSION['user'];
}

So that I could then use:


$userId = getUser()->userId;

however...this doens't work, something about calling a member function on a non object... This is pissing me off, because to me, those 'should' be equivalent statements pretty much.

If someone can tell me how to get this to work properly, it would be greatly appreciated.

Pete.

Hawkmoon
04-02-2004, 09:07 PM
I got the same problem, but it works if you just split


$userId = getUser()->userId;


into:


$userId = getUser();
$userId->userId;


Full Code:


<?
session_start();

class objFoo {
var $userId;

function objFoo() {
$this->userId = "bar";
}
}

$_SESSION['user'] = new objFoo();

function getUser() {
return $_SESSION['user'];
}

$userId = getUser();
echo($userId->userId);
?>

firepages
04-03-2004, 01:47 AM
<?
function getUser() {
return $_SESSION['user']->userID;
}
?>


would probably have done the job ?

but Hawkmoon's answer illustrates PHP4's lack of decent dereferencing which is AFAIK addressed in PHP5

nerhael
04-03-2004, 03:10 PM
Well that would work, if all I ever wanted was the user's Id. However, this is a big object, and I just wanted a convenient way of getting at all it's fields/methods.

Thanks for the replies though.

firepages
04-04-2004, 03:17 AM
you can use a generic getter , though there are debatable reasons some may suggest that makes this a bad idea ... but anyway (e.g. I disagree)



<?
function get_user_prop( $property ){
if( isset( $_SESSION['user']->$property ) ){
return $_SESSION['user']->$property ;
}
return false ;
}
$userId = get_user_prop( 'userId' ) ;
?>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum