[PHP] call_user_func(), call_user_func_array() など

<?php
function f($arg1, $arg2){
  return 'F | ' . $arg1 . $arg2 . "\n";
}
$c = function($arg1, $arg2){
  return 'C | ' . $arg1 . $arg2 . "\n";
};

if(
  ($f = call_user_func('f','x','y'))
  === call_user_func_array('f',array('x','y'))
)
  echo $f;

if(
  ($f = call_user_func($c,'b','a'))
  === call_user_func_array($c,array('b','a'))
)
  echo $f;

call_user_func(
  function(){
    echo 'hoge';
  }
);

call_user_func_array(
  function(){}
)

結果

F | xy
C | ba
hoge
( ! ) Warning: call_user_func_array() expects exactly 2 parameters, 1 given in *** on line 29
<?php
namespace x;

class C
{
  static public function f($arg1, $arg2){
    return 'F | ' . $arg1 . $arg2 . "\n";
  }
  public function g($arg1, $arg2){
    return 'G | ' . $arg1 . $arg2 . "\n";
  }
}
$c = new C;

$f = call_user_func(array($c,'f'), 'x', 'y');
if
(
  $f === call_user_func_array(
    __NAMESPACE__ . '\\C::f',
    array('x','y')
  )
  && $f === call_user_func_array(
    array(__NAMESPACE__ . '\\C', 'f'),
    array('x','y')
  )
)
  echo $f;

echo call_user_func(array(__NAMESPACE__ . '\\C', 'g'), '3', '7');

結果

F | xy

( ! ) Strict standards: call_user_func() expects parameter 1 to be a valid callback, non-static method x\C::g() should not be called statically in *** on line 29
G | 37

スタティックメソッド出ない場合に ::演算子でアクセスすると E_STRICT でるっぽい

function_exists(), get_defined_functions()

<?php
function a(){
  function b(){}
}
var_dump(function_exists('a'));

$functions = get_defined_functions();
foreach($functions as $k => $v){
  $first_order[] = $k;
}
var_dump($first_order);
var_dump(count($functions[$first_order[0]]));
var_dump($functions[$first_order[1]]);

a();
$functions = get_defined_functions();
var_dump($functions[$first_order[1]]);

結果

boolean true
array
  0 => string 'internal' (length=8)
  1 => string 'user' (length=4)
int 1753
array
  0 => string 'a' (length=1)
array
  0 => string 'a' (length=1)
  1 => string 'b' (length=1)

internal は定義済み関数。1700超えの数があるので出力は避けた。。

Share
関連記事