6

Possible Duplicate:
php function variable scope

I am using below code to test with a global variable. It seems that a global variable cannot be compared inside a function.

Why is it not displaying 'hello world' in the output?

Below is the code that I am trying:

<?php    
$bool = 1;

function boo() {
    if ($bool == 1) {
        $bool = 2;
        echo 'Hello World';    
    }
}
?> 

When I remove function boo(), 'hello world' is displayed. Why is it not displaying when function exists?

4
  • 4
    Where are you calling your function? Commented Dec 4, 2012 at 17:56
  • $bool is not defined in the function scope. You need to access it globally, or better, pass it to the function. Commented Dec 4, 2012 at 17:57
  • 1
    You never actually call the function. Then, even if you were, you wouldn't see your 'Hello Word' printed, because $bool doesn't exists in the function scope. Commented Dec 4, 2012 at 17:57
  • $bool is a Global variable, Right? so it should be accessed within function as well! Commented Dec 4, 2012 at 17:59

4 Answers 4

9

use global $var to access your variable

<?php    
$bool = 1;

function boo() {
    global $bool;
    if ($bool == 1) {
        $bool = 2;
        echo 'Hello World';    
    }
}

boo();
?>

Or a safer way using pointers would be to

function boo(&$bool) {
    if ($bool == 1) {
        $bool = 2;
        echo 'Hello World';
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I wouldn't recommend using globals, even if the OP asks for it.
6

Looks like homework, still:

<?php

$bool = 1;

boo();

function boo() {
global $bool;

if ($bool == 1) {
$bool = 2;
echo 'Hello World';

}


}
?> 

Or

<?php

$bool = 1;

boo(&$bool);

function boo(&$bool) {

if ($bool == 1) {
$bool = 2;
echo 'Hello World';

}


}
?> 

Comments

3

Call you function, and pass $bool as a parameter and return the value.

$bool = 1;
$bool = boo($bool);

function boo($bool) {

  if ($bool == 1) {
    $bool = 2;
    echo 'Hello World';    
  }

  return $bool;
}

2 Comments

you don't actually set the value of bool here to the global value - see my answer for the correct solution.
@OliverAtkinson You are right! I didn't realize the $bool was being updated, I just considered the Hello World.
0

use this way

$bool = 1;
function boo($bool) {

  if ($bool == 1) {
    $bool = 2;
    echo 'Hello World';    
  }
}
boo($bool);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.