13. What is the value displayed when the following is executed? Assume that the code was executed using the following URL:
testscrīpt.php?c=25
<?php
function process($c, $d = 25)
{
global $e;
$retval = $c + $d - $_GET['c'] - $e;
return $retval;
}
$e = 10;
echo process(5);
?>
A. 25
B. -5
C. 10
D. 5
E. 0
Answer:
This question is designed to test your knowledge of how PHP scopes variables when dealing with functions. Specifically, you must understand how the global statement works to bring global variables into the local scope, and the scope-less nature of superglobal arrays such as $_GET, $_POST, $_COOKIE, $_REQUEST and others. In this case, the math works out to 5 + 25 - 25 – 10, which is -5, or answer B.
14. Consider the following scrīpt:
<?php
function myfunction($a, $b = true)
{
if($a && !$b) {
echo "Hello, World!\n";
}
}
$s = array(
0 => "my",
1 => "call",
2 => '$function',
3 => ' ',
4 => "function",
5 => '$a',
6 => '$b',
7 => 'a',
8 => 'b',
9 => '');
$a = true;
$b = false;
/* Group A */
$name = $s[?].$s[?].$s[?].$s[?].$s[?].$s[?];
/* Group B */
$name(${$s[?]}, ${$s[?]});
?>
Each ? in the above scrīpt represents an integer index against the $s array. In order to display the Hello, World! string when executed, what must the missing integer indexes be?
A. Group A: 4,3,0,4,9,9 Group B: 7,8
B. Group A: 1,3,0,4,9,9 Group B: 7,6
C. Group A: 1,3,2,3,0,4 Group B: 5,8
D. Group A: 0,4,9,9,9,9 Group B: 7,8
E. Group A: 4,3,0,4,9,9 Group B: 5,8
Answer:
Functions can be called dynamically by appending parentheses (as well as any parameter needed) to a variable containing the name of the function to call. Thus, for Group A the appropriate index combination is 0, 4, 9, 9, 9, 9, which evaluates to the string myfunction. The parameters, on the other hand, are evaluated as variables dynamically using the ${} construct. This means the appropriate indexes for group B are 7 and 8, which evaluate to ${'a'} and ${'b'}—meaning the variables $a and $b respectively. Therefore, the correct answer is D.