Very basic function() related problem !!!

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
rahul.pache
Forum Newbie
Posts: 9
Joined: Thu Apr 10, 2008 4:07 am

Very basic function() related problem !!!

Post 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
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

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

Post 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;
}
 
User avatar
EverLearning
Forum Contributor
Posts: 282
Joined: Sat Feb 23, 2008 3:49 am
Location: Niš, Serbia

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

Post 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);
 
rahul.pache
Forum Newbie
Posts: 9
Joined: Thu Apr 10, 2008 4:07 am

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

Post by rahul.pache »

What is EVIL in making a variable GLOBAL.. or using Global variables... ? 8O
User avatar
EverLearning
Forum Contributor
Posts: 282
Joined: Sat Feb 23, 2008 3:49 am
Location: Niš, Serbia

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

Post by EverLearning »

Post Reply