How do i assign a variable in a function for use outside of

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
gotornot
Forum Commoner
Posts: 54
Joined: Fri Jul 31, 2009 2:30 am

How do i assign a variable in a function for use outside of

Post by gotornot »

Hi

I am trying to write an email function and ive hit a snag

I need to assign 2 variables in the function with the content of an html email and text email.

Is there anyway of declairing a variiable within a function for use outside of it in the code below?
Mark Baker
Forum Regular
Posts: 710
Joined: Thu Oct 30, 2008 6:24 pm

Re: How do i assign a variable in a function for use outside of

Post by Mark Baker »

Code: Select all

 
function assignVar() {
   return 5;
}
 
$result = assignVar();
//  $result is now available outside the function and contains the value 5
 

Code: Select all

 
function assignVar() {
   return array(5,10);
}
 
list($result1,$result2) = assignVar();
//  $result1 and $result2 are now available outside the function and contains the values 5 and 10 respectively
 

Code: Select all

 
$result1 = $result2 = null;
function assignVar(&$result1,&$result2) {
   $result1 = 5;
   $result2 = 10;
}
 
assignVar($result1,$result2);
//  $result1 and $result2 are now available outside the function and contains the values 5 and 10 respectively
 

Code: Select all

 
$result1 = $result2 = null;
function assignVar() {
   global $result1, $result2;
 
   $result1 = 5;
   $result2 = 10;
}
 
assignVar();
//  $result1 and $result2 are now available outside the function and contains the values 5 and 10 respectively
 
User avatar
jackpf
DevNet Resident
Posts: 2119
Joined: Sun Feb 15, 2009 7:22 pm
Location: Ipswich, UK

Re: How do i assign a variable in a function for use outside of

Post by jackpf »

+1 for the examples :)

If you're not able to return an array (or an object), I personally prefer passing by reference...since it gives more control as to what the variables are called etc...and if you need to call the function multiple times, you can have it assign the value(s) to different variables.
:)
Post Reply