0

我的代码比这复杂得多,但仅此而已:

$string = "wuddup";

function echothis() {
echo $string;
}

echothis();

有没有一种简单的方法可以做到这一点global $string

原因是,我有一个检查登录功能,有很多变量,我在函数之外有配置变量......

4

4 回答 4

3

Whatever happened to parameters?

function echothis($str) {
    echo $str;
}

echothis($string);

If you are having issues with managing variables and their scope, chances are you need to refactor your code structure.

于 2013-02-18T06:13:43.673 回答
1

只需创建一个类并向其添加静态变量。您可以从任何地方访问它,而无需创建该类的实例。

class base2 {
public static $var2 = 1;

}

参考如下

echo base2::$var2;
于 2013-02-18T06:14:42.903 回答
0

您可以让您的函数将变量作为参数或者包含所有这些参数的数组。

$all_variables = array(
  "string" => "wuddup",
  "number" => 6,
  "an_array" => array(1, 3, 4)
);

function example_func($args) {
  // does things
}

example_func($all_variables);

或者,您可以创建一个类并通过$this.

于 2013-02-18T06:15:55.433 回答
0

您可以将配置变量定义为常量并在函数内部调用它们。

于 2013-02-18T06:16:04.883 回答