访问函数内部的变量 - php

时间:2013-09-12 16:18:34

标签: php

我需要访问一个在函数中另一个php文件中声明的变量..我该怎么办?

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();
?>

现在我可以访问b.php文件中的“$ global ['words']”变量,但不能在函数内部,我怎样才能在函数内部看到它?

2 个答案:

答案 0 :(得分:1)

首选选项是作为参数传递:

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

fun($global);

如果由于某种原因你不能使用这种方法,那么你可以将变量声明为全局:

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

fun();

或使用$GLOBALS数组:

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

fun();

但一般来说,使用全局变量是considered bad practise

答案 1 :(得分:0)

实际上你的函数不知道它之外的任何东西,如果它不是类,或者像$_POST这样的全局php变量,你可以尝试将函数定义为:

function fun() use ($globals)
{

}
相关问题