Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/227.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 我在全局数组上设置的字段不存在_Php - Fatal编程技术网

Php 我在全局数组上设置的字段不存在

Php 我在全局数组上设置的字段不存在,php,Php,在我的PHP网页上,我有一个全局数组: $test = array(); 然后我调用这个函数: function f () { global $test; init( $test ); $test['foo'] // Error: undefined index "foo" } function init ( $test ) { $test['foo'] = 'bar'; $test['foo'] // evaluates to'bar' } 然

在我的PHP网页上,我有一个全局数组:

$test = array();
然后我调用这个函数:

function f () 
{
    global $test;

    init( $test );
    $test['foo'] // Error: undefined index "foo"
}
function init ( $test )
{
    $test['foo'] = 'bar';
    $test['foo'] // evaluates to'bar'
}
然后调用此函数:

function f () 
{
    global $test;

    init( $test );
    $test['foo'] // Error: undefined index "foo"
}
function init ( $test )
{
    $test['foo'] = 'bar';
    $test['foo'] // evaluates to'bar'
}

正如你所看到的,我犯了一个错误。我添加到
init()
中的数组中的“foo”字段没有保留。为什么会发生这种情况?我以为我是在
init()
内部对全局
$test
进行了变异,但似乎我没有这样做。这里发生了什么,如何在
init()
中设置一个持续存在的“foo”字段?

数组不会自动通过引用传递。所以在init$test中是数组的副本

你要么需要


或者更好的方法是从init返回它

如果要修改变量,必须通过引用传递该变量:

function init ( &$test )
{
    $test['foo'] = 'bar';
    $test['foo'] // evaluates to'bar'
}

您正在通过值而不是引用将
$test
传递到
init
init
内部的
$test
是一个局部变量,恰好包含全局
$test
的值

您需要通过更改
init
的函数签名,通过引用传递数组:

function init ( &$test )
{
    $test['foo'] = 'bar';
    $test['foo'] // evaluates to'bar'
}
init
中使用
global$test

function init ()
{
    global $test;

    $test['foo'] = 'bar';
    $test['foo'] // evaluates to'bar'
}
或者让
init
返回数组(这意味着您需要执行
$test=init($test);
):


您应该尽可能避免全局代码,因为它使您的代码更难长期维护run@WayneC我只有一个全局-
$page
,用于存储网页的所有信息。在我的所有职能中,我都与这个全球组织合作。我想我应该用一个Page类来代替,但我还没有学习类。我在PHPStorm中得到这样一条消息:“调用时间传递引用在PHP5.4中已被删除”您将引用放在了错误的位置,它需要在定义中,而不是在调用中。谢谢
:)
我在PHP中不知道这一点。