Click here to Skip to main content
15,891,864 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
why is there no blank screen or a warning in this code ?

When we use a local variable $result to display the output outside the function, I think we are using a local variable in the global scope and there must be at-least a no output screen or a warning.

But the output for this code is 9.
Sorry if this is a basic question, I tried but couldn't find an answer.

PHP
<?php

function add ($first, $second)
{

    $result = $first + $second;
    echo $result ;

}

add(4,5) ;

?>


Can anyone clarify ? Why ?
Posted
Updated 22-Oct-13 4:31am
v5
Comments
Captain Price 22-Oct-13 10:03am    
There's no error because your piece of code is correct. :)

By calling a function with a parameter declared as a local variable, you don't carry this local variable out of the scope, you are using the normal mechanism of call and parameter passing. So, no problem.

However, don't worry: you will be able to come across the situation when the code is really incorrect but no warning is issued, but don't rush to ask why, I'll answer you right now: because PHP sucks :-). You can successfully use it, but it's better not to think of it as of a serious programming language. Its main benefit is just that even the cheapest Web hosting plans will support PHP, unlike other server-side technologies.

—SA
 
Share this answer
 
v2
Comments
Captain Price 23-Oct-13 7:32am    
PHP sucks in a way and it rocks in another way. BTW 5ed !
Sergey Alexandrovich Kryukov 23-Oct-13 12:18pm    
Whatever suits you, right? Thank you, Captain.
—SA
Captain Price 23-Oct-13 12:46pm    
Of course, Sergey. You're welcome.
I think you've missed a fundamental step - that is, returning the result of the calculation.

I.e I think you'll find the following amenable to your wishes.

PHP
<?php

function add ($first, $second)
{
    $result = $first + $second;
    return $result ;
}

// just show the result, don't do anything else with it
echo add(4,5);

// grab the result, then print it. Can do something else after/before/instead of printing it.
$answer = add(4,5);
echo $answer;

?>
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900