Will_S
Will_S

Reputation: 71

function and not using Global

Hi I was wondering if someone could help me out. Ive tried Global but this is not what I want.

$i= 0

if(.....){
   echo "In this part";
   $i = 1;
}
else{
   echo "........";
   $i = 2;
}

function process(){
   echo $i;
}

Upvotes: 0

Views: 104

Answers (5)

Sure it will work with $_GLOBALS. Try this code by playing with $var variable

<?php

$i= 0;

$var=0;

if($var==0){
   echo "In this part";
$GLOBALS["i"]=1;

}
else{
   echo "........";
$GLOBALS["i"]=2;
}

process();

function process(){
   echo $GLOBALS["i"];
}


?>

Upvotes: 1

Varun Kumar
Varun Kumar

Reputation: 478

I think you are defining the function and not calling it after the if-else block. you can define it anywhere but call this function after the if-else block simply like

if(....){
echo "In this part";
$i = 1;
} 
else{
echo "........";
$i = 2;
}    

process();

Upvotes: 1

Ethan
Ethan

Reputation: 2784

I tested this and it worked for me the way i believe you would like it to work

$i= 0;

if(1==2){
echo "In this part";
$i = 1;
} 
else{
echo "........";
 $i = 2;
}

function process(){
 global $i;
 echo $i;
}

process();

Upvotes: 1

sathishkumar
sathishkumar

Reputation: 1816

Inside the function also you should declare the global variable.

function process(){
   global $i;
   echo $i;
}

Upvotes: 1

Muhammad Hasan Khan
Muhammad Hasan Khan

Reputation: 35126

Wouldn't it be better to just pass the stuff you need inside the method, as argument?

process($i);

function process($i){
   echo $i;
}

Upvotes: 8

Related Questions