14
14

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 5 years have passed since last update.

マジックメソッド__issetは無限ループする可能性がある

Last updated at Posted at 2016-06-12

問題点

PHPのマジックメソッド__issetは,無限ループを防ぐために**「直前の呼び出しと同じ引数で呼ばれたら〜」**という条件で判定を行っているとみられる.そのため…

<?php
class Storage
{
    public function __isset($key)
    {
        return isset($this->$key);
    }
}

$s = new Storage;
var_dump(isset($s->p)); // bool(false)

これを以下のような実装に変えてしまうと無限ループを引き起こし,php.iniの設定によってはクラッシュすることもある.

<?php
class Storage
{
    public function __isset($key)
    {
        return isset($this->{"_$key"});
    }
}

$s = new Storage;
var_dump(isset($s->p)); // Segmentation Fault または Fatal Error

解決策

__issetの実装の中で自分自身に対してプロパティの存在確認(とNULLチェック)を行いたい場合,property_existsで代用する.

<?php
class Storage
{
    public function __isset($key)
    {
        return property_exists($this, "_$key") && $this->{"_$key"} !== null;
    }
}

$s = new Storage;
var_dump(isset($s->p)); // bool(false)
14
14
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
14
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?