Page 1 of 1

Very basic function() related problem !!!

Posted: Thu Apr 10, 2008 4:23 am
by rahul.pache
I am using XAMPP {PHP 5}
Here is the code :

Code: Select all

 
<?php
$var=0;
function test() {
echo "<br> VAr : " . $var;
$var = 1;
echo "<br> VAr : " . $var;
}
test();
if($var == 1) {
 echo "Hello";
}
?>
I have taken 1 variable $var = 0; outside the function
And I want to use it inside the function. So that after changing its value it will be available to test and print "hello"

Plz suggest how to do that.
I WILL BE VERY VERY THANKFULLLLLLL

Re: Very basic function() related problem !!!

Posted: Thu Apr 10, 2008 4:33 am
by Benjamin
You should not be required to do it that way. There are better methods.

Here is a bad way to do it.

Code: Select all

 
$var = 1;
 
function test()
{
    $x =& $GLOBALS['var'];
    $x = 2;
}
 

Re: Very basic function() related problem !!!

Posted: Thu Apr 10, 2008 4:34 am
by EverLearning
One way to make $var available in function scope is to declare them global

Code: Select all

function test() {
    global $var;
// your code ...
}
But that way is EVIL.

Better is passing variable to a function by reference

Code: Select all

function test(&var) {
// your code ...
}
 
test($var);
 

Re: Very basic function() related problem !!!

Posted: Thu Apr 10, 2008 4:40 am
by rahul.pache
What is EVIL in making a variable GLOBAL.. or using Global variables... ? 8O

Re: Very basic function() related problem !!!

Posted: Thu Apr 10, 2008 5:04 am
by EverLearning