Global and Static Variables – Scope in PHP Functions


When you want to use variables outside your function for use within your function, you will have to use the keyword global. This will allow you to use variables declared outside of a function. It will even override the variables inside the function if they have the same name. You can also use it to access the variables inside the function from outside.

Global Variables

Using variables inside a function

Example:

Note: The value for the variable $name = Chris is used inside the function hello() because we declared it as global. The argument passed for the same variable $name is ignored or overridden.

Using Variables Outside a Function

Example:

Using $GLOBALS

If you prefer, you can use $GLOBALS instead of the keyword global. Here’s how you do it.

Example:

Notes:

  1. We used $GLOBALS to acces the variable $name declared outside the function.
  2. Again $GLOBALS[‘output’] is used so that the variable name $output is accessible outside the function. When you do this, there’s no need to return a value from the function itself.

Static Variables

Static variables are used so as to retain the values of variables even after a function is called. When a function is called for the second time, the changed value is not saved. So, to ensure that the value is saved, we use static variables.

Example:

Output:

Note: See how the value for the variable $total is retained every time the function is called.

You may also like

Comments are closed here.

Advertisements

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 2 other subscribers