PHP - 声明一个全局数组 [英] PHP - declare a global array

查看:144
本文介绍了PHP - 声明一个全局数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试在函数中使用数组时,存在未定义变量的问题。下面的代码就是一个例子。我怎么能够访问函数 hello()中的数组 $ prev ?我尝试过搜索,但当变量是​​数组时,我不知道如何使用 $ GLOBALS [$ varname]

I am having a problem of Undefined variable when I try to use an array inside a function. An example is the code below. How can I be able to access the array $prev inside the function hello()? I've tried searching but I don't really know how to use $GLOBALS[$varname] when the variable is an array. Thanks for any help!

<?php

$prev = [0,1,2];

function hello(){

    echo $prev[1];

}

hello();
hello();
hello();

?>


推荐答案

您也可以将该变量传递给函数:


You can also pass the variable into the function:

$prev = [0,1,2];

function hello(array $array){

    echo $array[1];

}

hello($prev);
hello($prev);
hello($prev);

?>

另一种方法是将变量引用

function hello(&$array){

    $array[1]++;
    echo $array[1];

}

这篇关于PHP - 声明一个全局数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆