Function Return Question

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
JakeJ
Forum Regular
Posts: 675
Joined: Thu Dec 10, 2009 6:27 pm

Function Return Question

Post by JakeJ »

The following line works just fine, but I want to put it in to a function:

Code: Select all

if(isset($_SESSION['v_p_first_name'])) { echo $SESSION['v_p_first_name']; } else { echo $clientinfo['p_first_name'];
I've got a ton of similar lines that need to do the same thing so I want to functionalize it. So far I have this:

Code: Select all

$_SESSION['v_p_first_name'] = "Jake";
$clientinfo['p_first_name'] = "Ben";
Function decide_data($input) {
	$vinput = 'v_'.$input;
	
If (isset($_SESSION[$vinput])){
	return $_SESSION[$vinput]; //this part works just fine.
}
Else {
	
	return //$clientinfo['p_first_name'];
}
}
echo decide_data('p_first_name')
  
The idea here is to use the field name as input for the function and have it return either the session data or the results of $clientinfo[]. It works for the session data, but I can't seem to get it to return the client data. It tells me that $clientinfo isn't set.

Thanks!
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: Function Return Question

Post by Benjamin »

$clientinfo is not in the same memory scope.
JakeJ
Forum Regular
Posts: 675
Joined: Thu Dec 10, 2009 6:27 pm

Re: Function Return Question

Post by JakeJ »

I found a work around... If I provide a second parameter for the function which includes $client_info['p_first_name'] and return that if session is not set then it works perfectly but it doesn't seem like the most elegant solution.

Got any other ideas?
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: Function Return Question

Post by Benjamin »

Another solution would be to make the variable global, which is bad practice.

Passing the variable as a parameter is not bad practice at all.

The best solution may be to create a class.
JakeJ
Forum Regular
Posts: 675
Joined: Thu Dec 10, 2009 6:27 pm

Re: Function Return Question

Post by JakeJ »

Thanks for the class idea. I'll keep that in mind for next time. But I was pressed for time so I just went with the extra parameter.
Post Reply