Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question

2 Answers 2

up vote 6 down vote accepted

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>';
}
share|improve this answer
    
ok i didnt know that, i'm new in php, i come from java and javascript...but i understand, thx! –  Andreas Daoutis May 22 '12 at 13:06

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;
}
share|improve this answer
1  
ok i understand! thanks! –  Andreas Daoutis May 22 '12 at 13:07
    
can you explain, why making it global would be a bad idea? –  Andreas Daoutis May 22 '12 at 13:11
2  
If you have too many global variables you can lose track of what's being used where, and then get two variable references using the same name (reference) without knowing it. This will lead to unexpected behaviour where one part of the code updates it without realising another part is also using it. –  Brad May 22 '12 at 13:19
    
ok thats a good point, but i think not a real problem. especially not for me, because it is a very small php file, but thanks for your answer. –  Andreas Daoutis May 22 '12 at 13:45

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.