【问题标题】:PHP - While/foreach in a class: stuck, can’t figure out what to doPHP - 类中的 While/foreach:卡住,不知道该怎么做
【发布时间】:2017-01-22 20:01:42
【问题描述】:

我正在学习(嗯,正在尝试)OOP,我有一个简单且可能非常愚蠢的问题。 我必须从一个非常“深”的数组中检索一些数据。如果我要使用过程方法,我会声明一个这样的变量,只是为了便于阅读:

    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 或同时保持干净/可读/可维护的代码?或者也许我应该使用不同的方法?

提前致谢!

【问题讨论】:

    标签: php arrays class foreach while-loop


    【解决方案1】:

    您需要将$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 ++$readable;一样是前增量,而不是后增量,这样方法才能返回更新后的值。

    【讨论】:

    • 只是一个旁注,注意foreach 循环中的return 语句。在当前场景中,一旦return 语句被命中,控制就会返回到调用函数语句。所以基本上,您的 foreach 循环将只执行一次
    • 谢谢!我曾想过将 $readable 作为参数,但我这样做只是为了 myCustomIncrement()。也非常感谢您的其他提示!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-15
    • 2017-05-05
    • 1970-01-01
    • 2014-02-28
    • 1970-01-01
    • 2020-11-24
    • 2015-12-26
    相关资源
    最近更新 更多