0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【PHP】__construct(コンストラクタ)の実践的なやつ

Last updated at Posted at 2022-03-07

コード

<?php
class Cat {
  public static $count = 0;
  public $name;
  public $age;

  public function __construct($name, $age){
    $this->name = $name;
    $this->age = $age;
    self::$count++;
  }
  public function introduce(){
    echo '名前は'.$this->name.'、' .$this->age.'歳です'.PHP_EOL;
  }
}
$cats = [];
$cats[] = new Cat('ポチ', 3);
$cats[] = new Cat('ミケ', 5);
$cats[] = new Cat('タマ', 4);
foreach($cats as $cat){
  $cat->introduce();
}
echo '動物の合計数:'.Cat::$count.'匹';

結果

名前はポチ、3歳です
名前はミケ、5歳です
名前はタマ、4歳です
動物の合計数:3匹

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?