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?

学習112日目

Posted at

テーマ

phpのクラスとインスタンスに関する特殊メソッドまとめ

目的

理解が曖昧なので整理

内容

コンストラクタ

とは?

  • インスタンス生成時に自動で呼ばれるメソッド
  • 初期化処理に利用

class User {
    public function __construct(private string $name) {
        echo "User {$this->name} created\n";
    }
}

$user = new User("Alice");

デストラクタ

とは?

  • インスタンス破棄時に自動で呼び出されるメソッド
  • リソース解放などに使用

class User {
    public function __destruct() {
        echo "User {$this->name} destroyed\n";
    }
}

$user = new User("Alice");

プロパティ取得ハンドラ

とは?

存在しない(またはアクセスできない)プロパティを参照したときに呼ばれる

class User {
    private array $data = ["name" => "Alice", "age" => 25];

    public function __get($name) {
        echo "Getting property {$name}\n";
        return $this->data[$name] ?? null;
    }
}

$user = new User();
echo $user->name; 
// 出力: Getting property name
// 結果: Alice

プロパティ設定ハンドラ

とは?

存在しない(またはアクセスできない)プロパティに代入したときに呼ばれる

class User {
    private array $data = [];

    public function __set($name, $value) {
        echo "Setting {$name} to {$value}\n";
        $this->data[$name] = $value;
    }

    public function __get($name) {
        return $this->data[$name] ?? null;
    }
}

$user = new User();
$user->age = 30;  
// 出力: Setting age to 30
echo $user->age; // 30

未定義メソッド呼び出しハンドラ

とは?

存在しないインスタンスメソッドを呼び出したときに実行される

class User {
    public function __call($name, $arguments) {
        echo "Method {$name} does not exist. Args: " . implode(", ", $arguments) . "\n";
    }
}

$user = new User();
$user->greet("Hello", "World");  
// 出力: Method greet does not exist. Args: Hello, World

コメント

引数との対応関係を丁寧に追って理解する必要がある。

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?