如何让函数外部的变量在函数中工作


How do I make a variable from outside a function work in that function?

function nothing() { 
    echo $variableThatIWant; 
}

你可以把"global"放在你想要使用的变量前面,像这样:

<?php
    $txt = "Hello";
    function Test() {
        global $txt;
        echo $txt;
    }
    Test();
?>

或者:你可以把它作为参数传递,像这样:

<?php
    $txt = "Hello";
    function Test($txt) {
        echo $txt;
    }
    Test($txt);
?>

来源:http://browse-tutorials.com/tutorial/php-global-variables

更好的方法是将其作为参数传递。

function nothing($var) {
    echo $var;
}
$foo = 'foo';
nothing($foo);

邪恶的方式,我不知道我为什么要给你们看这个,是使用全局。

function nothing() {
    global $foo;
    echo $foo;
}
$foo = 'foo';
nothing();

你必须使用global

$var = 'hello';
function myprint()
{
   global $var;
   echo $var;
}

如果在类内部,也可以使用类属性(或成员变量):

<?php
$myClass = new MyClass();
echo $myClass->nothing();
class MyClass {
  var $variableThatIWant = "something that I want";
  function nothing() { 
    echo $this->variableThatIWant; 
  }
}

Codepad示例

如果你想在函数内部修改它,你可以通过引用传递它,而不必返回它:

$a = "hello";
myFunction($a);
$a .= " !!";
echo $a; // will print : hello world !!
function myFunction(&$a) {
  $a .= " world";
}

Codepad示例