2
0

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 static修飾子

Last updated at Posted at 2021-04-18

はじめに

PHPのオブジェクト思考について学習している際に、static修飾子の挙動がわかりづらかったので調べました。(自分メモ)

アクセス修飾子

アクセス修飾子としてよく使われるものは3つ。

  • public・・・どこからでもアクセス可能
  • private・・・同じクラス内からアクセス可能
  • protected・・・クラス内とクラスを継承した子クラスからアクセス可能

static修飾子とは

・あるクラスの全てのオブジェクトが一つの変数を共有したい時にグローバル変数を使わずに共有可能。
・クラスのインスタンスを生成することなく(つまりnewせずに)、staticで定義されたプロパティやメソッドを利用できる。

animal.php
//動物クラスを定義
class Animal {
    public $name;
    public static $category = "動物";
}
$cat = new Animal();
$cat->name = "ネコさん";
$dog = new Animal();
$dog->name = "イヌさん";

echo $cat->name;        //ネコさん
echo $cat::$category;   //動物

echo $dog->name;        //イヌさん
echo $dog::$category;   //動物

// newしなくても使える
echo Animal::$category; //動物

上記の$cat::$category;$dog::$category;はインスタンスとして静的プロパティを用いているが、Animal::$category;はインスタンスを生成せずにプロパティを用いることができている。このようにオブジェクトのインスタンスを生成せずに呼び出すことができる
このため、擬似変数$thisは、staticとして宣言されたメソッドの中から呼び出すことはできない。

2
0
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?