Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access a global variable in a PHP function

Tags:

scope

php

According to the most programming languages scope rules, I can access variables that are defined outside of functions inside them, but why doesn't this code work?

<?php     $data = 'My data';      function menugen() {         echo "[" . $data . "]";     }      menugen(); ?> 

The output is [].

like image 733
Amin Gholibeigian Avatar asked Mar 28 '13 16:03

Amin Gholibeigian


People also ask

Which keyword is used to access global variables PHP?

PHP The global Keyword The global keyword is used to access a global variable from within a function.

How do you define a variable accessible in function in PHP script?

To access the global variable within a function, use the GLOBAL keyword before the variable. However, these variables can be directly accessed or used outside the function without any keyword.

Why not use global variables PHP?

That's because variables aren't really global in PHP. The scope of a typical PHP program is one HTTP request. Session variables actually have a wider scope than PHP "global" variables because they typically encompass many HTTP requests.


1 Answers

It is not working because you have to declare which global variables you'll be accessing:

$data = 'My data';  function menugen() {     global $data; // <-- Add this line      echo "[" . $data . "]"; }  menugen(); 

Otherwise you can access it as $GLOBALS['data']. See Variable scope.

Even if a little off-topic, I'd suggest you avoid using globals at all and prefer passing as parameters.

like image 75
Matteo Tassinari Avatar answered Sep 30 '22 03:09

Matteo Tassinari