Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/275.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 从类外访问ForEach中的变量_Php_Class_Variables_Foreach_Variable Variables - Fatal编程技术网

Php 从类外访问ForEach中的变量

Php 从类外访问ForEach中的变量,php,class,variables,foreach,variable-variables,Php,Class,Variables,Foreach,Variable Variables,我有一个类,为了便于理解,为了举例起见,它接受一个关联数组,在其上循环,并基于键指定一个变量名,然后为其赋值。 这在课堂上很管用: class showItems { static public function list(){ foreach ($list as $name => $value) { $$name = $value; } // This works here echo $title; // This is the vari

我有一个类,为了便于理解,为了举例起见,它接受一个关联数组,在其上循环,并基于键指定一个变量名,然后为其赋值。 这在课堂上很管用:
class showItems {

  static public function list(){
    foreach ($list as $name => $value) {
      $$name = $value;
    }
    // This works here
    echo $title; // This is the variable I want Which is being set in the foreach.
    break;

  }

}
上面的类很好用,并且$title可以是echo'd。 然而,从类外访问该变量是我运气不佳的地方。我尝试了我能想到的所有类型的过程

$showItems = new showItems();
$showItems::list();

// Cannot grasp what I need to do here to echo the value I want.
$showItems::list()->$title; // This returns "Trying to get property of non-object"

?>

执行类似于
$TestItems=newtestitems()
的操作,然后执行
TestItems->list()
并使list函数
返回$title

  • 不要在
    列表中
    回显

  • 您可以通过
    访问
    静态
    列表
    方法,如下所示:
    showItems::list()

  • 您没有将参数传递给
    列表
    方法,这非常奇怪,正如您所说的那样

  • 获取关联数组

  • 您的
    $list
    方法内部似乎未初始化

  • 如果只想调用
    静态方法,则无需实例化

  • 现在还不清楚你想做什么,所以请重新措辞你的问题,并在这篇文章中写一条评论,我将编辑我的答案,以进一步帮助你


  • 函数
    showItems
    返回什么?很明显,在类中运行的foreach循环中,我可以回显$title,因此我知道它正在工作,不用担心其余的代码。但是-如何从类外部检索$title变量?您可以在showItems类中创建名为$title的静态成员,并为其创建一个getter。然而,如果某些东西看起来“有效”,那就不一定是正确的。