0
1

More than 1 year has passed since last update.

【PHP】__construct(コンストラクタ)の練習

Posted at

コード

<?php
class Dog {
    private $name;
    private $weight;
    private $height;

    public function __construct($name, $weight,$height){
        $this->name = $name;
        $this->weight = $weight;
        $this->height = $height;
    }

    public function introduce(){
          $this->introduce_name();
          $this->introduce_weight();
          $this->introduce_height();
    }
    private function introduce_name(){
        echo '僕の名前は'. $this->name. 'だワン!'.PHP_EOL;
    }
    private function introduce_weight(){
        echo '僕の体重は'. $this->weight.'kgだワン!'.PHP_EOL;
        echo ($this->weight < 10 ? '小型犬だワン!' : '中型犬以上だワン!').PHP_EOL;
    }
    private function introduce_height(){
      echo '僕の体長は'. $this->height.'cmだワン!'.PHP_EOL;
    }
}
$hati = new Dog('ハチ', 9,70);
$hati->introduce();

結果

僕の名前はハチだワン!
僕の体重は9kgだワン!
小型犬だワン!
僕の体長は70cmだワン!
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1