LoginSignup
2
0

More than 5 years have passed since last update.

PHP: clone $this が書かれた親クラスを継承したとき、小クラスの振る舞いはどうなるのか?

Last updated at Posted at 2018-05-29

clone $thisが書かれた親クラスを継承したとき、小クラスの振る舞いはどうなるのか?」 疑問だったので調べた。

このような継承関係のあるクラスで、

class ParentClass {}

class ChildClass extends ParentClass {}

親クラスにclone $thisを書いたとき、

class ParentClass
{
    public function copy(): self
    {
        return clone $this;
    }
}

次のコードで、$objParentClassになるのか、それともChildClassになるのか?

$child = new ChildClass(); // 小クラス
$obj = $child->copy(); // 親クラスの実装 clone $this が呼ばれる
// $objはParentClass? ChildClass?

正解は、ChildClass

assert(get_class($obj) === 'ChildClass');
2
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
2
0