php - Function in array executed before calling it -
i have array this:
$cmds = array( 'info' => call_user_func('_info', $cmd1), 'e1' => 'something' );
the func itself:
function _info($cmd1){ if(strlen($cmd1) < 2){ die('invalid username'); }else{ echo 'cmd1 > 2';} }
the problem being executed before call giving undefined variable error because $cmd1
not exist yet, exist when call in foreach
function. been searching solution hours didn't find. tried setting array
'info' => _info($cmd1)
, 'info' => '_info'
, putted $cmd1
directly in func
function _info(){ if(strlen($cmd1) < 2){die('invalid'); }
but still same error being called before want be.
you can send parameters executed later
$cmds = array( 'info' => [ '_info', '$cmd1' ], // single quotes 'e1' => 'something' );
in meantime cmd1 defined
$cmd1 = "hello"; foreach ($cmds $key => $cmdset) { if (!is_array($cmdset)) { // e1 => } else { $function = array_shift($cmdset); foreach ($cmdset &$param) { // variables treated below, values passed through if (stripos($param, '$') === 0) { // remove $ $cmd1 = substr($param, 1); // set param value of cmd1 $param = $$param; // variable varaible $$ } } call_user_func_array($function, $cmdset); } }
while works bad practice this. depending on variable function not clear if set or not. code hard understand.
you should think solution can ensure $cmd1
set or can retrieved , if not have way deal well.
Comments
Post a Comment