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。然而,如果某些东西看起来“有效”,那就不一定是正确的。