はじめに
マジックメソッドについて整理する。2回目。
__toStringメソッド
print命令などでオブジェクトの文字列表現を要求された際
参考コード
Person.php
class Person
{
public $firstName;
public $lastName;
// 中略
public function __toString() : string
{
return $this->lastName.$this->firstName;
}
}
toString.php
require_once 'Person.php';
$p = new Person('太郎', '山田');
print $p; // 山田太郎
__invokeメソッド
オブジェクトが関数の形式で呼び出された際。
参考コード
FliendList.php
class FliendList implements IteratorAggregate
{
// 中略
private array $list = [];
public function getIterator()
{
return new ArrayIterator($this->list);
}
public function add(Person $p): void
{
$this->list[] = $p;
}
}
invoke.php
require_once 'Person.php';
require_once 'FliendList.php';
$list = new FliendList();
$list->add(new Person('太郎', '山田'));
$list->add(new Person('奈美', '掛谷'));
$list->add(new Person('賢', '高江'));
print $list(1); // 結果:掛谷奈美
__cloneメソッド
clone命令でオブジェクトを複製した際。
参考コード
オブジェクトの内容をディープコピーしたい際に使う。
FliendList.php
class FliendList implements IteratorAggregate
{
// 中略
public function __clone() : void
{
foreach ($this->list as &$value) {
$value = clone $value;
}
}
}
clone_deep.php
require_once 'Person.php';
require_once 'FliendList.php';
$list = new FliendList();
$list->add(new Person('太郎', '山田'));
$list->add(new Person('奈美', '掛谷'));
$list->add(new Person('賢', '高江'));
$list2 = clone $list;
var_dump($list2(1) === $list(1)); // 結果:bool(false)