Jump to content

Make local function var into GOBAL var. PHP


SpeedCrazy

Recommended Posts

Hey Guys,

I need to make a local function variable into a Global variable for access outside of the function in PHP. I have a feeling if i figured out classes i would be able to do it without using functions but currently i need them.

Any ideas?

Thanks,

Speed

Share this post


Link to post
Share on other sites

Hey Guys,

I need to make a local function variable into a Global variable for access outside of the function in PHP. I have a feeling if i figured out classes i would be able to do it without using functions but currently i need them.

Any ideas?

Thanks,

Speed

Is there a reason you can't return the variable from the function itself to use it? If you can't simply return the value, I would look to see if using a class made sense. If you don't want to mess with classes then you can make the variable global in scope (see this page)

Share this post


Link to post
Share on other sites

  • 2 months later...
Guest johnBMitchell

Below is the code showing how variables can be declared inside the function as global. I hope you will get solution from this.

 

<?php 
$v1="Hello 1"; 

function test(){ 
    echo "The value of \$v1= $v1"; 
    // The above line will print The value of $v1= 
    global $v1; 
    echo "<br>The value of \$v1= $v1"; 
    // The above line will print The value of $v1= Hello 1 
    $v2="Hello 2"; 
} 
test(); 
echo "<br>The value of \$v2=$v2"; 
// The above line will print The value of $v2= 
?>

Share this post


Link to post
Share on other sites

I recomend using a function with return() as flareback stated. Though it is possible to do what you want... here are some examples:

 

<?php
// Example 1 - Return value from function
$test_1 = testFunction1();

function testFunction1(){
return '1';
}
$test_1 += 1;

echo 'Output of test 1:<br />';
echo $test_1; // outputs '2'
echo '<br /><br />';


// Example 2 - Declare global using variable outside of function
$test_2 = 100;
testFunction2();
function testFunction2(){
global $test_2;
$test_2 += 99;
}
$test_2 +=1;

echo 'Output of test 2:<br />';
echo $test_2; // outputs '200'
echo '<br /><br />';



// Example 3 - Declare global using variable inside of function
$test_3 = 9999;
testFunction3();
function testFunction3(){
global $test_3;
$test_3 = 4;
$test_3 += 1;
}
$test_3 += 5;

echo 'Output of test 3:<br />';
echo $test_3; // outputs '10'
?>

Share this post


Link to post
Share on other sites

Please sign in to comment

You will be able to leave a comment after signing in



Sign In Now
×
×
  • Create New...