Q
What is the output of the following PHP code?

<?php
$num = 10;
function testScope() {
global $num;
echo $num;
}
testScope();
?>

Answer & Solution

Answer: Option A
Solution:
The output of the code will be 10 because the $num variable is declared as global inside the testScope() function using the global keyword, allowing it to access the global variable with the same name declared outside the function.
Related Questions on Average

Which of the following statements about variable scope in PHP functions is true?

A). Variables defined inside a function have global scope

B). Variables defined outside a function have local scope

C). Variables defined inside a function have local scope

D). Variables defined outside a function have global scope

What is the output of the following PHP code?

<?php
function greet() {
echo 'Hello, World!';
}
if (function_exists('greet')) {
greet();
} else {
echo 'Function does not exist';
}
?>

A). Hello, World!

B). Function does not exist

C). Undefined function: greet

D). Function greet() { echo 'Hello, World!'; }

What is the purpose of the return statement in PHP functions?

A). To terminate the function execution

B). To output a value from the function and terminate its execution

C). To define the function name

D). To declare a variable within the function

Which of the following statements is true about function names in PHP?

A). Function names are case-sensitive

B). Function names must start with a dollar sign ($)

C). Function names cannot contain numbers

D). Function names can contain spaces

What is the output of the following PHP code?

<?php
function multiply(...$args) {
$result = 1;
foreach ($args as $value) {
$result *= $value;
}
return $result;
}
echo multiply(2, 3, 4);
?>

A). 24

B). 9

C). 6

D). 2

What will be the output of the following PHP code?

<?php
$greet = function($name) {
return 'Hello, $name!';
};
echo $greet('John');
?>

A). Hello, John!

B). Hello, $name!

C). function($name) {
return 'Hello, $name!';
}

D). John

Which of the following statements about return types in PHP functions is true?

A). PHP functions must always have a return type

B). PHP functions can have a return type specified using the 'returns' keyword

C). PHP functions can have a return type specified using the 'return' keyword

D). PHP functions can have a return type declared using type declarations

Which PHP feature allows passing a function as an argument to another function?

A). Dynamic functions

B). Global functions

C). Static functions

D). Callbacks

Which PHP feature allows defining functions without specifying their names?

A). Anonymous functions

B). Dynamic functions

C). Global functions

D). Static functions

What keyword is used to define a function in PHP?

A). define

B). function

C). declare

D). method