0

i need to access a variable which is declared in another php file within a function.. How can i do it?

a.php

<?php

$global['words']=array("one","two","three");

echo "welcome"
?>

b.php

<?php

$words = $global['words'];
require_once('a.php');

print_r($global['words']);

function fun()
{

print_r($global['words']); // not displaying here

}

fun();
?>

now i am able to access the "$global['words']" variable in b.php file, but not within function, how can i make it visible inside the function?

mark
  • 21,691
  • 3
  • 49
  • 71
thuk
  • 263
  • 3
  • 7
  • 21
  • 1
    Have a look at [this](http://stackoverflow.com/questions/14913718/global-variables-in-a-loaded-page/14913814#14913814) – Vedant Terkar Sep 12 '13 at 16:25

2 Answers2

1

The preferred option is to pass as a parameter:

function fun($local) {
    print_r($local['words']);
}

fun($global);

If for some reason you can't use that approach, then you can declare the variable as global:

function fun() {
    global $global;
    print_r($global['words']);
}

fun();

Or use the $GLOBALS array:

function fun() {
    print_r($GLOBALS['global']['words']);
}

fun();

But in general, using global variables is considered bad practise.

Community
  • 1
  • 1
cmbuckley
  • 40,217
  • 9
  • 77
  • 91
0

actually your function does n't know about anything outside it, if it's not a classes, or global php vars such as $_POST , you can try to define function as:

function fun() use ($globals)
{

}
fthiella
  • 48,073
  • 15
  • 90
  • 106
karaken
  • 94
  • 3