1

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?

2 Answers 2

6

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>';
}
Sign up to request clarification or add additional context in comments.

1 Comment

ok i didnt know that, i'm new in php, i come from java and javascript...but i understand, thx!
3

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;
}

3 Comments

can you explain, why making it global would be a bad idea?
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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.