misima
misima

Reputation: 423

I can not access the global variable in function in included file

I can not access the global variable in function in included file

sample files : dl.dropbox.com/u/9486036/similasyon.zip

simulations:

index.php:

<?

function init(){
    include "init.php";
}

init();

?>

init.php:

<?

$data = "data_string";

echo "Data-test in ".__FILE__.": <b>".$data."</b><br />\r\n"; 

include "php/funcs.php";

?>

funcs.php:

<? 

echo "Data-test in ".__FILE__.": <b>".$data."</b><br />\r\n";

function func_load()
{
    global $data;
    echo "Data-test in ".__FILE__." in function func_load(): <b>".$data."</b><br />\r\n";

    include dirname(__FILE__)."/funcs/sub_func.php";
}

func_load();

?>

sub_func.php:

<? 
    echo "Data-test in ".__FILE__.": <b>".$data."</b><br />\r\n";
?>

screen output:

Data-test in \similasyon\init.php                             : data_string 
Data-test in \similasyon\php\funcs.php                        : data_string 
Data-test in \similasyon\php\funcs.php in function func_load():  
Data-test in \similasyon\php\funcs\sub_func.php               :

Upvotes: 1

Views: 153

Answers (4)

NullUserException
NullUserException

Reputation: 85458

Think about what you are doing for a second. After all the includes are done, you end up with something like this:

<?php

function init(){
    $data = "data_string";

    echo "Data-test in ".__FILE__.": <b>".$data."</b><br />\r\n"; 
    echo "Data-test in ".__FILE__.": <b>".$data."</b><br />\r\n";

    function func_load()
    {
        global $data;
        echo "Data-test in ".__FILE__." in function func_load(): <b>".$data."</b><br />\r\n";
        echo "Data-test in ".__FILE__.": <b>".$data."</b><br />\r\n";
    }

    func_load();
}

init();

?>

Basically, $data is not in the global scope. You'll have to change your init() to something like:

function init(){
    global $data;
    include "init.php";
}

Although you should seriously consider restructuring the code, because this just doesn't look good.

Especially having includes within includes when they all belong to the same function body.

Upvotes: 2

Treffynnon
Treffynnon

Reputation: 21553

If you change:

<?

function init(){
    include "init.php";
}

init();

?>

To

<?

function init(){
    global $data;
    include "init.php";
}

init();

?>

Then it should work.

Upvotes: 1

Vladimir Fesko
Vladimir Fesko

Reputation: 222

You can make $data really global to use it everywhere with global keyword:

function init(){
    global $data;
    include "init.php";
}

init();

Upvotes: 1

JRSofty
JRSofty

Reputation: 1256

That is because the initial include is also wrapped in a function and the would need a global $data inside it like this in your index.php

 function init(){
      global $data;
      include "init.php";
 }
 init();

Upvotes: 2

Related Questions