1
0

マジックメソッド①

Posted at

はじめに

マジックメソッドとは

あらかじめ特定の役割を与えられたメソッド。
シグネチャ(名前、引数、戻り値の組み合わせ)と呼び出しのタイミングが決められていて、中身(機能)がないため、必要に応じて自分で実装する必要がある。

__getメソッド

未定義のプロパティを取得しようとした際

__setメソッド

未定義のプロパティを設定しようとした際

参考コード

to, subject, messageだけを定義しておいて、それ以外のプロパティは__get/__setメソッドで処理させている。

MyMail.php
class MyMail
{
    public string $to;
    public string $subject;
    public string $message;

    private array $headers = [];

    public function __set(string $name, string $value)
    {
        $this->headers[$name] = $value;
    }

    public function __get(string $name): string
    {
        return $this->headers[$name];
    }

    public function send()
    {
        $others = '';
        foreach ($this->headers as $key => $value) {
            $key = str_replace('_', '-', $key);
            $others .= "$key: $value\n";
        }
        mb_send_mail($this->to, $this->subject, $this->message, $others);
    }
}
get_set.php
require_once 'MyMail.php';

$m = new MyMail();
$m->to = 'test@example.com';
$m->subject = 'Test';
$m->message = 'Hello, World!';
$m->From = 'admin@example.com';
$m->X_Mailer = 'MyMail 1.0';
$m->X_Priority = '1';
$m->X_MSMail_Priority = 'High';
$m->send();

__issetメソッド

未定義のプロパティをisset関数で処理しようとした際

__unsetメソッド

未定義のプロパティをunset関数で処理しようとした際

参考コード
MyMail.php
class MyMail
{
    // 中略
    public function __isset(string $name): bool
    {
        return isset($this->headers[$name]);
    }

    public function __unset(string $name)
    {
        unset($this->headers[$name]);
    }
    // 中略
}
isset_unset.php
require_once 'MyMail.php';

$m = new MyMail();
$m->From = 'admin@example.com';
var_dump($m->From); // 結果:string(17) "admin@example.com"
var_dump(isset($m->From)); // 結果:bool(true)
unset($m->From);
var_dump($m->From); // 結果:NULL

__callメソッド

未定義のインスタンスメソッドをコールした際

__callStaticメソッド

未定義の静的メソッドをコールした際

参考コード

引数が渡されなかったらメソッド名に対応するキーの値を取得。
引数が渡されなければメソッド名に対応するキーに引数の値を設定。

MyMail.php
class MyMail
{
    // 中略
    public function __call(string $name, array $args): mixed
    {
        if (count($args) === 0) {
            return $this->headers[$name];
        } else {
            $this->headers[$name] = $args[0];
        }
    }
    // 中略
}
call.php
require_once 'MyMail.php';

$m = new MyMail();
$m->From('admin@example.com');
print $m->From(); //結果:admin@example.com
1
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
1
0