Page 1 of 1

Function Return Question

Posted: Tue Jun 01, 2010 12:26 am
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!

Re: Function Return Question

Posted: Tue Jun 01, 2010 12:28 am
by Benjamin
$clientinfo is not in the same memory scope.

Re: Function Return Question

Posted: Tue Jun 01, 2010 12:39 am
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?

Re: Function Return Question

Posted: Tue Jun 01, 2010 12:43 am
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.

Re: Function Return Question

Posted: Tue Jun 01, 2010 1:35 am
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.