Reputation: 13
First of all I'm very sorry for my irrelevant question title, as I did not know how to write it better.
To start with, I am a PHP beginner. I am solving some PHP exercise and I came upon a question I don't know where to start with:
function q3() {
// I am supposed to write stuff here and not change anything to get the question right.
}
function a3($admin = false) {
assertion_group("Question 3");
foreach ($GLOBALS as $k => $v) $$k = $v;
if ($admin) {
$file = q3("edsi.pem");
}
$key = @file_get_contents($file);
$key = substr($key, 0, 4);
assert($key == substr(file_get_contents(__FILE__), 0, 4));
return $key;
}
First of all, I understand what $GLOBALS
does, but why assign the $$k
to $v
(so the $k value to the $v value)? And does $GLOBALS
get the values within functions?
How can I set $admin = true
? I believe through q3()
, but I don't see how...
Next thing that confuses me most is: $file = q3("edsi.pem")
. As my q3 function doesn't have any arguments, and that I'm not supposed to add one, how can I use that?!
Thank you all very much in advance for your answer. My apologies again for the very vague question...
EDIT:
With the help of @mario to better understand this whole mess, basically what I had to put in q3 was:
if ($info == 'edsi.pem') {
$info = __FILE__;
return $info;
}
plus add an argument for q3
(q3($info)
) and add ?admin=true
in the header...
Many thanks again!
Upvotes: 0
Views: 88
Reputation: 145482
First of all, I understand what $GLOBALS does, but why assign the $$k to $v (so the $k value to the $v value)? And does $GLOBALS get the values within functions?
What that foreach … $$k = $v;
snippet does is basically extract($GLOBALS);
This isn't a very useful way to pass arguments around. Using global vars only makes sense if they have somewhat descriptive names, and if they're not misused as state flags between different code sections.
And no, globals aren't available in all functions right away. Read up on variable scope.
How can I set $admin = true? I believe through q3(), but I don't see how...
You are confusing the function names here (precisely because they aren't rather useful function names to begin with). You can pass the $admin parameter when calling a3()
instead:
a3(true);
Next thing that confuses me most is: $file = q3("edsi.pem"). As my q3 function doesn't have any arguments, and that I'm not supposed to add one, how can I use that?!
The only way to get the argument in q3
is per func_get_arg()
.
And again really, unless this is an exercise about how not to write code or a tutorial about weird use cases, you shouldn't really bother further.
Upvotes: 2