Examveda

What will be the output of the following PHP code?
<?php
$op2 = "blabla";
function foo($op1)
    {
        echo $op1;
        echo $op2;
    }
foo("hello");
?>

A. helloblabla

B. Error

C. hello

D. helloblablablabla

Answer: Option B

Solution (By Examveda Team)

The correct answer is Option B: Error

Here's why:

In PHP, variables defined outside of a function are not automatically accessible inside the function.

Scope is a crucial concept in programming.

The variable `$op2` is defined outside the function `foo()`.

Inside `foo()`, you are trying to use `$op2` without it being defined within the function's scope.

Therefore, PHP will throw an error (specifically, a notice about an undefined variable) when trying to access `$op2` within the function.

Although the `echo $op1` will work fine , but after that when trying to access the `$op2` that is not defined inside the function scope it will throw error .

To make `$op2` accessible inside the function, you would need to either:
1. Pass it as an argument to the function.
2. Use the `global` keyword to bring it into the function's scope.

Since neither of these is done in the given code, an error occurs.

This Question Belongs to PHP >> Functions

Join The Discussion

Comments (1)

  1. Shariq Bhutto
    Shariq Bhutto:
    7 months ago

    this code will throw an error because the variable $op2 is defined outside the function foo(), and it is not accessible inside the function due to variable scope rules in PHP.

Related Questions on Functions