从外部类访问ForEach中的变量变量

时间:2014-06-28 17:29:52

标签: 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 variable I want Which is being set in the foreach.
    break;

  }

}

上面的类工作正常,$ title可以回显。 但是,从课堂外访问该变量是我没有运气的地方。我已经尝试了我能想到的所有类型的流程。

$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"

?>

2 个答案:

答案 0 :(得分:1)

执行$TestItems=new testItems()然后TestItems->list()之类的操作,并使列表功能return $title

答案 1 :(得分:1)

  1. 不要在echo方法中list

  2. 您可以通过static这样的list发送class方法:showItems::list()

  3. 您没有将参数传递给list方法,这非常奇怪,因为您已声明

  4.   

    采用关联数组

    1. $list方法中的list似乎未初始化。

    2. 如果您只想调用class方法,则无需实例化static

    3. 目前还不清楚你要做什么,所以请重新提一下你的问题,并在这篇文章中写评论,这样我就会编辑我的答案来帮助你。

相关问题