面向对象的 PHP 中的 for 循环

通过使用面向对象的 Php 概念,这是根据给定条件执行的代码块。计数器应该从 0 1 2 3 4 5 开始计数,直到达到指定的数字...但这里不是按预期工作


//考虑下面的代码


class Counter{

    public $number;

    public function setCounter($number){

        $this->number = $number;

    for($this->number ;$this->number < 10 ; $this-> number ++){

       }

    }

    public function getCounter(){

        echo $this->number;

    }

}

$counter= new Counter();

$counter->setCounter(0);

$counter->getCounter();


小唯快跑啊
浏览 129回答 1
1回答

肥皂起泡泡

我不完全确定你要做什么,但作为学习练习,你只需要echo循环执行后的数字,所以它是10。要获取每个数字,您需要echo在循环中使用它。其中之一,尽管这可能不是总体上最好的模式:要么摆脱getCounter:class Counter{&nbsp; &nbsp; public $number;&nbsp; &nbsp; public function setCounter($number){&nbsp; &nbsp; &nbsp; &nbsp; $this->number = $number;&nbsp; &nbsp; &nbsp; &nbsp; for($this->number ;$this->number < 10 ; $this-> number ++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; echo $this->number;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;$counter= new Counter();$counter->setCounter(0);或者在循环中调用它:class Counter{&nbsp; &nbsp; public $number;&nbsp; &nbsp; public function setCounter($number){&nbsp; &nbsp; &nbsp; &nbsp; $this->number = $number;&nbsp; &nbsp; &nbsp; &nbsp; for($this->number ;$this->number < 10 ; $this-> number ++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $this->getCounter();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; public function getCounter(){&nbsp; &nbsp; &nbsp; &nbsp; echo $this->number;&nbsp; &nbsp; }}$counter= new Counter();$counter->setCounter(0);和/或添加一个count方法:class Counter{&nbsp; &nbsp; public $number;&nbsp; &nbsp; public function setCounter($number){&nbsp; &nbsp; &nbsp; &nbsp; $this->number = $number;&nbsp; &nbsp; }&nbsp; &nbsp; public function getCounter(){&nbsp; &nbsp; &nbsp; &nbsp; echo $this->number;&nbsp; &nbsp; }&nbsp; &nbsp; public function count() {&nbsp; &nbsp; &nbsp; &nbsp; for($this->number ;$this->number < 10 ; $this-> number ++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $this->getCounter();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;$counter= new Counter();$counter->setCounter(0);$counter->count();
打开App,查看更多内容
随时随地看视频慕课网APP