Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Really simple function variable transfer question: 1

Status
Not open for further replies.

mancroft

Programmer
Joined
Oct 26, 2002
Messages
267
Location
GB
Really simple function variable transfer question:

What is the best way to get $thevariable from fun1 into fun2 so it can be echoed?

Code:
function fun1(){

$thevariable = 'mick43';

}

function fun2(){

echo $thevariable;

}
 
function fun1(){

$thevariable = 'mick43';
fun2($thevariable);
}

function fun2($param1){

echo $param1;

}
 
The scope of a variable within a function is local to the function unless the variable name is taken from the global space. If you want the variable to be in the global space:
Code:
func1(){
   # make var global
   global $theVariable;
   $theVariable = "whatever";
   func2();
}
# similarly
func2(){
   # globalize
   global $theVar;
   echo $theVar;
}

In ingresman's post there is passing of values not the identical variable. You could achieve basically the same thing by passing the variable by reference.
In both cases I described the variable exists in the global scope. If you don't want that you still could pass it to the second function per reference:
Code:
func1(){
   $theVariable = "whatever";
   func2(&$theVariable);
}
# similarly
func2(&$myVar){
   echo $myVar;
}
The thing is that when passed per reference by manipulating $myVar in func2() the value of $theVariable in func1() will be changed:
Code:
func1(){
   $theVariable = "whatever";
   func2(&$theVariable);
   echo $theVariable;
}
# similarly
func2(&$myVar){
   echo $myVar;
   $myVar = "NewValue";
}
This will first echo "whatever" and then "NewValue".
 
Why not an object? :o) he he..

Code:
class my_var {

    var $theVariable;

    function set($value){
        $this->theVariable=$value;
    }

    function to_string(){
        echo $this->theVariable;
    }
}

$TheVar=New my_var;
$TheVar->set("mick43");
$theVar->to_string();
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top