How the variable scope works in PHP

Follow by Email
Facebook0
Facebook
Google+
https://codingsec.net/2016/11/variable-scope-works-php/

Scope refers to the visibility of a variable in the PHP script. A variable defined inside a function will have local scope i.e., within the function. A variable outside the function can have the same name as a local variable in a function, where the local variable has higher precedence over the outer variable.

In some cases, a function might need access to a variable declared outside the function definition. In such cases, global declaration can be used before the variable name which allows the accessibility of the variable that is declared outside the function definition. Below example demonstrates local and global variables:

In the above example, first print statement gives 100 and the second print statement gives 110.

The lifetime of a normal variable in a function is until the function execution completes. Sometimes, there might be a need to retain the value of a variable between function calls. In such cases, the variable must be declared with static. The lifetime of static variable is until the execution of script completes. Below example demonstrates the use of static variables:

In the above example, the print statement prints 10 instead of 0.

As in any typical programming language, parameters in a function definition are known as formal parameters and the parameters in a function call are known as actual parameters. The number of formal parameters and normal parameters may not be equal.

The default parameter passing mechanism is pass-by-value where a copy of the actual parameters are passed to actual parameters. Below example demonstrates pass-by-value:

After the above code is executed the values of a and b remains 10 and 20 even after the function call.

Take your time to comment on this article.

Follow by Email
Facebook0
Facebook
Google+
https://codingsec.net/2016/11/variable-scope-works-php/

Add a Comment

Your email address will not be published. Required fields are marked *

Like the article? please consider sharing it. Thank you

Advertisment ad adsense adlogger