42
47

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.

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

Last updated at Posted at 2014-11-08

はじめに

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

実行コード

<?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
42
47
1

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
42
47

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?