PHP - Question about specifying variable with global scope outside of a function - php

I understand that if you declare a variable within a php function with the 'global' keyword it will reference a variable declared outside the function, but why would a php programmer want to declare a variable outside of a function scope as 'global?' Thanks!
I understand what this does:
<?
$a = 1;
function $boo() {
global $a;
echo $a;
}
?>
But what I'm getting at is why would I want to do this?
<?
global $a;
function $boo() {
//foo
}
?>

It has to do with php scope
If you have file a.php that has a class like this
<?
class test()
{
function test()
{
include('b.php');
}
}
?>
and a file b.php
<?
$a = 1;
?>
Then $a will only be accessible in the scope of function test()
if you have global $a in b.php, $a then becomes a global variable
here's the php doc about it : http://php.net/manual/en/function.include.php

I have no idea why you would want to do that. For all intents and purposes (unless I am very, very much mistaken) this is exactly the same as just:
<?
var $a;
function $boo() {
// foo
}
?>
Which in turn is the very same as
<?
function $boo() {
// foo
}
?>
because you generally don't have to instantiate your variables in PHP.
Very curious why you're using variably-named functions though? (function $boo() {} )

Well, IMHO the use of global variables is a poor programming practice. It can cause unintended side-effects in your program which are hard to debug, and makes it harder to maintain.

Related

What is the best way to acces language variables in a function?

Basically, I've included my language file in my page, in that language file are arrays like $lang['ERROR']['TITLE'], so my question is: what is the best way to acces those variables in functions?
You could use one of two methods depending on what you want:
1) Declare a global variable:
<?php
$GLOBALS['lang'] = $lang;
function test () {
echo $GLOBALS['lang']['ERROR']['TITLE'];
}
test();
?>
This makes it able to be used inside any function.
2) Pass it to the function:
function test ($var) {
echo $var;
}
test ($lang['ERROR']['TITLE']);
This only allows for it inside the one specific function.
You can try something like this:
<?php
$lang = ...;
function test () {
global $lang;
echo $lang['ERROR']['TITLE'];
}
test();
?>
The global-keyword is needed, to tell php that it should look for this variable in the global-scope. Otherwise, $lang is undefined.
You need to use the global keyword at the top of your function to access a variable defined outside the function. Eg:
function test() {
global $lang;
echo $lang['ERROR']['TITLE'];
}

What is the scope of global PHP variables in a Drupal page?

Consider this PHP script:
<?php
$a = "ok";
function foo() {
global $a; print "[$a]";
}
foo();
?>
It prints [ok] when run with a PHP interpreter as one would expect. But it prints just [] if run in a Drupal page. To make it work in Drupal I have to add another global specification before the variable declaration thus:
<?php
global $a; // WHY IS THIS NEEDED IN DRUPAL?
$a = "ok";
function foo() {
global $a; print "[$a]";
}
foo();
?>
Likely because Drupal includes the file inside a function:
function render() {
include 'my_script.php';
}
That makes $a local to the function, not global.

How can I emulate PHP's crazy global thing?

If I have a file a.php which I can't edit.
<?php
$a = 1;
function a() {
global $a;
echo $a;
}
a();
then running php a.php prints 1 nicely. But if I have b.php:
<?php
function b() {
include "a.php";
}
b();
Then running php b.php doesn't print anything.
What can I type before the include "a.php" to make it behave the same without editing a.php?
(Obviously other than defining $a. In my real-world example it has to work for a complicated a.php).
Try adding a global into your new function:
function b() {
global $a;
include "a.php";
}
At the moment I wonder if PHP is treating $a as local to your b() function.
Addendum: in response to your comment, it seems that you need to grab arbitrary variables that your include has created locally in your function, and remake them as global. This works for me on 5.3.20 on OSX 10.6.8:
function b() {
include 'a.php';
// Move variables into global space
foreach (get_defined_vars() as $name => $value) {
global $$name;
// global wipes the value, so just reset it
$$name = $value;
echo "Declared $name as global\n";
}
}
b();
// Your global vars should be available here
Obviously you can remove the echo once you're happy it works.
Defining a function inside a function? Yuck. But I guess you have a real-world situation that doesn't allow any other way. But for the record, this is REALLY BAD PRACTICE
Adding global $a to b() should work.
function b() {
global $a;
include "a.php";
}
I don't know what variables need to be defined. a.php is really complicated
Then the only way I can think of is not using a function in b.php, so you're in the global scope when including a.php. I can see no other way.
It sounds like a.php is some legacy or 3rd party script that you have to wrap in your own application. I had a similar problem once and the solution was not pretty. First, you will have to find out, what global variables exist (grep global or similar helps).
This is the relevant part of my "Script Adapter" class:
private function _includeScript($file, $globals)
{
foreach ($globals as $global) {
global $$global;
}
ob_start();
require $file;
$this->_response->setBody(ob_get_clean());
}
As you see, I had to catch the output too. The class also emulates $_GET and catches header calls to assign everything to a Response object, but for your case only this method is important. It gets called with the file name and an array of global variable names as parameters:
_includeScript('a.php', array('a'));

PHP variable defined outside callback function is unaccessible inside the function

I'm trying to use $variable inside my callback function. I pass it to another function like this: functionName("egTraders_ItemDataBound"), inside that function I assign it to a variable and the call it like this: $theAssignedFunctionVariable($this, $rowToAdd);
And the function egTraders_ItemDataBound gets called properly but the variable $variable
is undefined. What can I do?
<?php
$variable = "var";
function egTraders_ItemDataBound($sender, $param1) {
echo $variable;
}
?>
If You are running PHP 5.3+ You can achive this by simply creating anonymous functioin with use keyword ( documentation ) :
$bar = 'bar';
$f = function() use ($bar)
{
var_dump($bar);
};
function bar( $fName )
{
$fName();
}
bar($f);
You could pass it in as a param or you could use it as a global in the function. I do not recommend the latter. You should stay away from globals.
Edit for example
$variable = "var";
function egTraders_ItemDataBound($sender, $param1) {
global $variable;
echo $variable;
}
egTraders_ItemDataBound(NULL, NULL);
you need to declare the variable as global because it is out of scope
$variable = "var";
function egTraders_ItemDataBound($sender, $param1) {
global $variable;
echo $variable;
}
The variable is declared outside of the scope of the function. You should revisit your design. I strongly recommend against using global variables as that is poor practice.

Declaring a global variable inside a function

I have two PHP files. In the first I set a cookie based on a $_GET value, and then call a function which then sends this value on to the other file. This is some code which I'm using in join.php:
include('inc/processJoin.php');
setcookie("site_Referral", $_GET['rid'], time()+10000);
$joinProc = new processJoin();
$joinProc->grabReferral($_COOKIE["site_Referral"]);
The other file (processJoin.php) will then send this value (among others) to further files which will process and insert the data into the database.
The problem I'm having is that when the grabReferral() function in processJoin.php is called, the $referralID variable isn't being defined on a global scale - other functions in processJoin.php can't seem to access it to send to other files/processes.
I've tried this in processJoin.php:
grabReferral($rid) {
global $ref_id;
$ref_id = $rid;
}
someOtherFunction() {
sendValue($ref_id);
}
But the someOtherFunction can't seem to access or use the $ref_id value. I've also tried using define() to no avail. What am I doing wrong?
you have to define the global var in the second function as well..
// global scope
$ref_id = 1;
grabReferral($rid){
global $ref_id;
$ref_id = $rid;
}
someOtherFunction(){
global $ref_id;
sendValue($ref_id);
}
felix
personally, I would recommend the $GLOBALS super variable.
function foo(){
$GLOBALS['foobar'] = 'foobar';
}
function bar(){
echo $GLOBALS['foobar'];
}
foo();
bar();
DEMO
This is a simple and working code to initialize global variable from a function :
function doit()
{
$GLOBALS['val'] = 'bar';
}
doit();
echo $val;
Gives the output as :
bar
The following works.
<?php
foo();
bar();
function foo()
{
global $jabberwocky;
$jabberwocky="Jabberwocky<br>";
bar();
}
function bar()
{
global $jabberwocky;
echo $jabberwocky;
}
?>
to produce:
Jabberwocky
Jabberwocky
So it seems that a variable first declared as global inside a function and then initalised inside that function acquires global scope.
The global keyword lets you access a global variable, not create one. Global variables are the ones created in the outermost scope (i.e. not inside a function or class), and are not accessible inside function unless you declare them with global.
Disclaimer: none of this code was tested, but it definitely gets the point across.
Choose a name for the variable you want to be available in the global scope.
Within the function, assign a value to the name index of the $GLOBALS array.
function my_function(){
//...
$GLOBALS['myGlobalVariable'] = 42; //globalize variable
//...
}
Now when you want to access the variable from code running in the global scope, i.e. NOT within a function, you can simply use $ name to access it, without referencing the $GLOBALS array.
<?php
//<global scope>
echo $myGlobalVariable; //outputs "42"
//</global scope>
?>
To access your global variable from a non-global scope such as a function or an object, you have two options:
Access it through the appropriate index of the $GLOBALS array. Ex: $GLOBALS['myGlobalVariable'] This takes a long time to type, especially if you need to use the global variable multiple times in your non-global scope.
A more concise way is to import your global variable into the local scope by using the 'global' statement. After using this statement, you can reference the global variable as though it were a local variable. Changes you make to the variable will be reflected globally.
//<non global scopes>
function a(){
//...
global $myGlobalVariable;
echo $myGlobalVariable; // outputs "42"
//...
}
function b(){
//...
echo $GLOBALS['myGlobalVariable']; // outputs "42"
echo $myGlobalVariable; // outputs "" (nothing)
// ^also generates warning - variable not defined
//...
}
//</non global scopes>
Please use global variables in any language with caution, especially in PHP.
See the following resources for discussion of global variables:
http://chateau-logic.com/content/dangers-global-variables-revisited-because-php
http://c2.com/cgi/wiki?GlobalVariablesAreBad
The visibility of a variable
I hope that helped
<?php
$a = 1;
$b = 2;
function Sum()
{
global $a, $b;
$b = $a + $b;
}
Sum();
echo $b;
?>

Categories