1
1

More than 1 year has passed since last update.

【PHP】クラスのstatic(スタティック)はなぜ使うのか?

Last updated at Posted at 2022-03-04

※staticをなぜ使うか?

インスタンスの生成を省略できる※他はわからん

<?php

class Food
{
    static $cat = "キャットフード";
    static $dog = "ドッグフード";
    static $bird = "パフ・ザ・フルーツ";
    
    static function cry($animal) {
        if($animal === 'cat') return self::$cat;
        if($animal === 'dog') return self::$dog;
        if($animal === 'bird') return self::$bird;
    }
}

echo "猫の餌:".Food::cry('cat');
echo PHP_EOL;
echo "犬の餌:".Food::cry('dog');
echo PHP_EOL;
echo "鳥の餌:".Food::cry('bird');

結果

猫の餌:キャットフード
犬の餌:ドッグフード
鳥の餌:パフ・ザ・フルーツ
1
1
6

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
1
1