【问题标题】:Accessing variable inside function - php [duplicate]访问函数内部的变量 - php [重复]
【发布时间】:2013-09-17 03:31:09
【问题描述】:

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

一个.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']”变量,但不能在函数内访问,我怎样才能使其在函数内可见?

【问题讨论】:

标签: php


【解决方案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

【讨论】:

  • 这与我的回答有何不同?
  • 因为我建议使用参数,这是正确的方法(无论 OP 是否要求)。
  • 仍然,有什么不同?
  • 非常感谢您的回答,cbuckley..
【解决方案2】:

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

function fun() use ($globals)
{

}

【讨论】:

  • use 关键字仅适用于匿名函数。
  • 谢谢我忘了(
猜你喜欢
  • 2017-07-14
  • 2020-06-16
  • 2019-06-14
  • 2021-05-15
  • 1970-01-01
  • 2014-04-08
  • 2015-04-29
  • 2017-02-02
相关资源
最近更新 更多