PHP find output programs (User-defined functions) | set 1

Find the output of PHP programs | User-defined functions | Set 1: Enhance the knowledge of PHP User-defined functions concepts by solving and finding the output of some PHP programs.
Submitted by Nidhi, on January 22, 2021

Question 1:

<?php
    function fun()
    {
        printf("Hello World");
    }
    echo ("Hello India");
?>

Output:

Hello India

Explanation:

In the above program, we defined a user-define function. But we did not call function fun() anywhere then it will not print "Hello World", only "Hello India" will print on the webpage.

Question 2:

<?php
    fun();
    
    function fun()
    {
        printf("Hello World<br>");
    }
    
    echo ("Hello India");
?>

Output:

Hello World
Hello India

Explanation:

In the above program, we defined a user define function. Then we called function fun() then it will print "Hello World", and  "Hello India" will print on the webpage.

Question 3:

<?php
    $A = 5;
    $B = 10;
    
    fun($A, $B);
    printf("%d, %d", $A, $B);
    
    function fun(int $A, int $B)
    {
        $A = 20;
        $B = 30;
    }
?>

Output:

5, 10

Explanation:

In the above program, we defined a user define function fun() that contains two parameters $A and $B. We modified the values of $A and $B, but it will not reflect at the calling position. Because here we used the call by value mechanism for parameter passing. Then "5,10" will be printed on the webpage.

Question 4:

<?php
    $A = 5;
    $B = 10;
    
    fun(&$A, &$B);
    printf("%d, %d", $A, $B);
    
    function fun(int $A, int $B)
    {
        $A = 20;
        $B = 30;
    }
?>

Output:

PHP Parse error:  syntax error, unexpected '&' in 
/home/main.php on line 5

Explanation:

The above program will generate syntax error because we cannot use ampersand '&' operator in the function call. To implement call by reference mechanism for parameter passing. We need to use ampersand '&' operator in the function definition.

Question 5:

<?php
    $A = 5;
    $B = 10;
    
    fun($A, $B);
    printf("%d, %d", $A, $B);
    
    function fun(int & $A, int & $B)
    {
        $A = 20;
        $B = 30;
    }
?>

Output:

20, 30

Explanation:

In the above program, we defined a user define function fun() that contains two parameters $A and $B. We modified the values of $A and $B, but it will also reflect at calling position. Because here we used the call by reference mechanism for parameter passing. Then "20,30" will be printed on the webpage.





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.