PHP-While/foreach在一个类中:卡住了,可以’;我不知道该怎么办
我正在学习(嗯,尝试)面向对象编程,我有一个简单而且可能非常愚蠢的问题。 我必须从一个非常“深”的数组中检索一些数据。如果我使用过程方法,我会声明这样一个变量,只是为了可读性:PHP-While/foreach在一个类中:卡住了,可以’;我不知道该怎么办,php,arrays,class,foreach,while-loop,Php,Arrays,Class,Foreach,While Loop,我正在学习(嗯,尝试)面向对象编程,我有一个简单而且可能非常愚蠢的问题。 我必须从一个非常“深”的数组中检索一些数据。如果我使用过程方法,我会声明这样一个变量,只是为了可读性: foreach ( $my_array as $single ) { $readable = $single['level_1']['level_2']['level_3']['something']; } 在foreach中,我可以随意使用$readable。 现在我正在尝试构建一
foreach ( $my_array as $single ) {
$readable = $single['level_1']['level_2']['level_3']['something'];
}
在foreach中,我可以随意使用$readable
。
现在我正在尝试构建一个类,我需要处理相同的数组。为了让事情变得更清楚,我很想这样做:
class MyClass {
protected $my_array = null;
protected function myCustomIncrement() {
return $readable++;
}
public function myCustomOutput() {
foreach ( $this->my_array as $single ) {
$readable = $single['level_1']['level_2']['level_3']['something'];
return $this->myCustomIncrement();
}
}
}
$test = new MyClass;
echo $test>myCustomOutput();
但是在myCustomIncrement()
内部时,$readable
或$this->$readable
结果未定义。我可能正试图做一些非常愚蠢的事情,这就是我想寻求帮助的原因:我如何使用foreach或同时保持干净/可读/可维护的代码?或者我应该用另一种方法
提前谢谢 您需要将
$readable
值传递给myCustomIncrement()
方法,并使其在那里递增。因此,您的myCustomIncrement()
和myCustomOutput()
方法如下:
protected function myCustomIncrement($readable) {
return ++$readable;
}
public function myCustomOutput() {
foreach( $this->my_array as $single ) {
$readable = $single['level_1']['level_2']['level_3']['something'];
return $this->myCustomIncrement($readable);
}
}
使增量操作预增量,如
return++$可读
,而不是post increment,这样方法就可以返回更新后的值。只是一个旁注,注意foreach
循环中的return
语句。在当前场景中,一旦命中return
语句,控件将返回到调用函数语句。所以基本上,您的foreach
循环只执行一次。谢谢!我曾想过将$readable作为参数,但我只为myCustomIncrement()这样做。非常感谢你的其他建议!