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

PHP インスタンス化

Last updated at Posted at 2025-09-17

PHPでのインスタンス化についてまとめる

インスタンス化とは

  • クラスをもとにオブジェクトを作成するプロセスのこと

書き方

$object = new ClassName();

$objectが新しく生成されたインスタンス

インスタンス化のメリット

  • 複数のオブジェクトを生成することで、それぞれのオブジェクトが独立したプロパティ(データ)を持つことができる
  • 一度クラスを定義すれば、何度でもnew演算子を使ってインスタンスを生成できる
  • メンテナンス性が向上する

例:

class User {
    public $name;

    public function introduce() {
        return "こんにちは、私の名前は" . $this->name . "です。";
    }
}

$user1 = new User();
$user1->name = "アリス";

$user2 = new User();
$user2->name = "ボブ";

echo $user1->introduce(); // 出力: こんにちは、私の名前はアリスです。
echo $user2->introduce(); // 出力: こんにちは、私の名前はボブです。
  • Userという同じクラスから、$user1$user2という2つの異なるインスタンスが作成され、それぞれ独立したnameプロパティを持っている
0
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
0
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?