简体   繁体   中英

Function in PHP doesn't return the value of my Array, why?

I have a little snippet of code and i can't make it work.

$dict = array('401003' => "Test")
function getID ($tempid) {
    $id = '<span title="'.$tempid.'">'.$dict[$tempid].'</span>';
    return $id;
}
echo getID('401003');
echo $dict['401003'];

I expected to get the 'Test' twice, but only the second echo returned me the 'Test'. Something seems to be wrong with the $dict[$tempid] in the function

Can you guys help me please?

This is to do with the variable scope , you do not have access to the $dict variable inside your function. You can work around this by declaring $dict as global, or by passing it to your function, you could refactor it like this:

function getID($tempId, $dict) {
    return '<span title="'.$tempid.'">'.$dict[$tempid].'</span>';
}

getID don't see your array, you have to add it as parameter or make $dict global which is generaly bad idea:

$dict = array('401003' => "Test")
function getID ($tempid) {
    global $dict;
    $id = '<span title="'.$tempid.'">'.$dict[$tempid].'</span>';
    return $id;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM