1
1

More than 1 year has passed since last update.

【PHP】staticはなぜ使うのか?※__constructと組み合わせることで最大の効果を発揮する

Last updated at Posted at 2022-03-07

static単体では【インスタンスを省略】だけだが、__constructと組み合わせることで
各インスタンスメリットの共通データや、各インスタンスメソットで使わない処理を書くことができる
それがstaticメソット

<?php
class Animal
{
    private static $animals = [];
    function __construct($name, $food) {
        $this->name = $name;
        $this->food = $food;
        array_push(self::$animals, '【'.$name.'】');
    }
    static function list() {
        echo join("と", self::$animals)."の食べ物を紹介します" . PHP_EOL;
    }
    function eat() {
        echo $this->name . "は" . $this->food . "を食べます" . PHP_EOL;
    }
}

$data = [
    ['name' => '猫','feed' => 'キャットフード'],
    ['name' => '犬','feed' => 'ドッグフード'],
    ['name' => '鳥','feed' => 'パフ・ザ・フルーツ'],
];
foreach ($data as $list) $animal[] = new Animal($list['name'],$list['feed']);
Animal::list();
foreach ($animal as $list) $list->eat();

結果

【猫】と【犬】と【鳥】の食べ物を紹介します
猫はキャットフードを食べます
犬はドッグフードを食べます
鳥はパフ・ザ・フルーツを食べます
1
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
1
1