Last active
December 18, 2015 21:09
-
-
Save ha1t/5845524 to your computer and use it in GitHub Desktop.
PHPオブジェクトにおける、シャローコピーとディープコピー
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Player extends stdClass | |
{ | |
public function __clone() | |
{ | |
$this->status = clone $this->status; | |
} | |
} | |
$player = new Player(); | |
$status = new stdClass(); | |
$status->level = 35; | |
$player->name = 'ポカパマズ'; | |
$player->status = $status; | |
$player2 = clone $player; | |
var_dump($player->name, $player->status->level); | |
var_dump($player2->name, $player2->status->level); | |
echo PHP_EOL; | |
// $player の 値を変更する | |
$player->name = 'オルテガ'; | |
$player->status->level = 52; | |
var_dump($player->name, $player->status->level); | |
var_dump($player2->name, $player2->status->level); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
string(15) "ポカパマズ" | |
int(35) | |
string(15) "ポカパマズ" | |
int(35) | |
string(12) "オルテガ" | |
int(52) | |
string(15) "ポカパマズ" | |
int(35) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$player = new stdClass(); | |
$status = new stdClass(); | |
$status->level = 35; | |
$player->name = 'ポカパマズ'; | |
$player->status = $status; | |
$player2 = clone $player; | |
var_dump($player->name, $player->status->level); | |
var_dump($player2->name, $player2->status->level); | |
echo PHP_EOL; | |
// $player の 値を変更する | |
$player->name = 'オルテガ'; | |
$player->status->level = 52; | |
// オルテガだけ変えたつもりなのにポカパマズもレベル52になってしまう | |
var_dump($player->name, $player->status->level); | |
var_dump($player2->name, $player2->status->level); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
string(15) "ポカパマズ" | |
int(35) | |
string(15) "ポカパマズ" | |
int(35) | |
string(12) "オルテガ" | |
int(52) | |
string(15) "ポカパマズ" | |
int(52) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment