1
1

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.

深い位置のプロパティにいきなり代入する

Posted at

PHPで深い位置のプロパティに、いきなり値を代入したいが
次のようなコードでは、警告が発生してしまう。

$a = new stdClass;
$a->b->c = 1; //代入はできるが警告が出る

マジックメソッド__get()を利用することで、目的が達成できた。

class exClass{
    function __get($name){
        $this->$name = new self;
        return $this->$name;
    }
}

$a = new exClass;
$a->b->c = 1; //成功

ただし問題があって、未定義のプロパティをgetした場合は、exClassオブジェクトが返ってくる。

1
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?