PHP

<値型>と<参照型>、<値渡し>と<参照渡し>について実行例を出す(PHP編)

More than 3 years have passed since last update.


はじめに

僕ぺちぱーだからぺちぴーしか読めないので書きました


実行コード

<?php

function swapAndEditValVal(array $left, array $right) {
$tmp = $left;
$left = $right;
$right = $tmp;
$tmp['value'] *= 100;
}
function swapAndEditRefVal(stdClass $left, stdClass $right) {
$tmp = $left;
$left = $right;
$right = $tmp;
$tmp->value *= 100;
}
function swapAndEditValRef(array &$left, array &$right) {
$tmp = $left;
$left = $right;
$right = $tmp;
$tmp['value'] *= 100;
}
function swapAndEditRefRef(stdClass &$left, stdClass &$right) {
$tmp = $left;
$left = $right;
$right = $tmp;
$tmp->value *= 100;
}

call_user_func(function () {
echo "値の値渡し\n";
$left = ['value' => 1];
$right = ['value' => 2];
swapAndEditValVal($left, $right);
printf("%d, %d\n", $left['value'], $right['value']);
});
call_user_func(function () {
echo "参照の値渡し\n";
$left = (object)['value' => 1];
$right = (object)['value' => 2];
swapAndEditRefVal($left, $right);
printf("%d, %d\n", $left->value, $right->value);
});
call_user_func(function () {
echo "値の参照渡し\n";
$left = ['value' => 1];
$right = ['value' => 2];
swapAndEditValRef($left, $right);
printf("%d, %d\n", $left['value'], $right['value']);
});
call_user_func(function () {
echo "参照の参照渡し\n";
$left = (object)['value' => 1];
$right = (object)['value' => 2];
swapAndEditRefRef($left, $right);
printf("%d, %d\n", $left->value, $right->value);
});


実行結果

値の値渡し

1, 2
参照の値渡し
100, 2
値の参照渡し
2, 1
参照の参照渡し
2, 100