无法从php访问全局数组

时间:2013-05-12 12:16:42

标签: php wordpress global

我在wordpress主题中遇到以下情况,我想在名为navigation.php的文件中修改

$array_test = array (1,2,3,4);

function func1()
{
  global $array_test;

  echo "test"; // to ensure that the function has been called
  echo $array_test[2]; // this writes nothing, though the function is being called
}

在名为header.php的文件中调用函数func1,仍然无法访问$array_test[2]的值,

你有什么想法吗?

编辑: 我怀疑这是wordpress或主题的问题,但我不确定 主题是免费的health_care_wp_theme

1 个答案:

答案 0 :(得分:2)

在navigation.php中,(如果该文件中没有类,则定义一个)

class Nav
{ 
     public $array_test = array(1,2,3,4);

     public function func1()
     {  
       echo "test"; // to ensure that the function has been called
       return $this->array_test[2]; 
     }

     public function access_within_class()
     {   
       print_r($this->array_test); 
     }     
}

在header.php中

include 'path/to/navigation.php';

$nav = new Nav();
$the_array = $nav->func1(); 
echo $the_array;