亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

面向對象的 PHP 中的 for 循環

面向對象的 PHP 中的 for 循環

PHP
小唯快跑啊 2023-06-24 17:28:46
通過使用面向對象的 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();
查看完整描述

1 回答

?
肥皂起泡泡

TA貢獻1829條經驗 獲得超6個贊

我不完全確定你要做什么,但作為學習練習,你只需要echo循環執行后的數字,所以它是10。要獲取每個數字,您需要echo在循環中使用它。其中之一,盡管這可能不是總體上最好的模式:


要么擺脫getCounter:


class Counter{

    public $number;

    public function setCounter($number){

        $this->number = $number;

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

            echo $this->number;

        }

    }

}        

$counter= new Counter();

$counter->setCounter(0);

或者在循環中調用它:


class Counter{

    public $number;

    public function setCounter($number){

        $this->number = $number;

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

            $this->getCounter();

        }

    }

    public function getCounter(){

        echo $this->number;

    }

}

$counter= new Counter();

$counter->setCounter(0);

和/或添加一個count方法:


class Counter{

    public $number;

    public function setCounter($number){

        $this->number = $number;

    }

    public function getCounter(){

        echo $this->number;

    }

    public function count() {

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

            $this->getCounter();

        }

    }

}        

$counter= new Counter();

$counter->setCounter(0);

$counter->count();


查看完整回答
反對 回復 2023-06-24
  • 1 回答
  • 0 關注
  • 156 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號