Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP global variables not working inside a function [duplicate]

Tags:

php

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?

like image 261
Clarsen Avatar asked Dec 04 '12 17:12

Clarsen


People also ask

Can we use global variable inside function PHP?

Global variables refer to any variable that is defined outside of the function. Global variables can be accessed from any part of the script i.e. inside and outside of the function. So, a global variable can be declared just like other variable but it must be declared outside of function definition.

What does $globals mean in PHP?

$GLOBALS is a PHP super global variable which is used to access global variables from anywhere in the PHP script (also from within functions or methods). PHP stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable.

Can we declare same variable in two times globally?

A variable or function can be declared any number of times, but it can be defined only once. (Remember the basic principle that you can't have two locations of the same variable or function).

Which PHP keyword is used to access a global variable inside the function?

PHP The global Keyword The global keyword is used to access a global variable from within a function.


1 Answers

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';
    }
}
like image 165
Oliver Atkinson Avatar answered Sep 20 '22 13:09

Oliver Atkinson