5
5

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.

call_user_funcで引数を参照渡しする

Last updated at Posted at 2012-04-18

call_user_func()による関数呼び出しでは引数を参照で渡すことができません。(正確に言うと「できはしますが、エラーが発生するため推奨されません」)

<?php
function testRef(&$a) {
  $a = 1;
}

testRef($b);
//$b === 1になる

call_user_func('testRef', $c); //エラー発生
call_user_func('testRef', &$c); //deprecatedな書き方

しかし、call_user_func_array()を使うと参照渡しが可能です。配列に参照として変数を組み込んでおけば良いです。

<?php
function testRef(&$a) {
  $a = 1;
}
call_user_func_array('testRef', array(&$c)); //エラーが起きない
//$c === 1になる

裏ワザちっく。そのうち潰される書き方なのかな?

5
5
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
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?