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.
Related
Why is $a not printing?
And what is the alternate of this, and I dont want to use return.
function abc () {
$a = 'abc';
global $a;
}
abc();
echo $a;
The reason why it's not echoing is because of two things:
1) You need to declare global "before" the variable you wish to define as being global.
and
2) You also need to call the function.
Rewrite:
<?php
function abc()
{
global $a;
$a = 'abc';
}
abc();
echo $a;
For more information on variable scopes, visit the PHP.net website:
http://www.php.net/manual/en/language.variables.scope.php
You can get your variable as:
echo $GLOBALS['a'];
see http://php.net/manual/en/language.variables.scope.php
You can use define():
function abc() {
define("A", "abc");
}
abc();
echo A;
Make sure you call the function. I added that just above echo.
First you must create and assign a variable. And then in you function describe that is a global var you want to use.
$a = 'zxc';
function abc() {
global $a;
$a = 'abc';
}
abc();
echo $a;
This is not really good idea to use golbal such way. I don't really understand why I so much want to use a global var...
But my opinion is better for you to use a pointer to variable.
function abc(&$var){
$var = 'abc';
}
$a = 'zxc';
abc(&$a);
echo $a;
Or even would be better to create an object and then access variable with-in this object
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'));
I have 2 files. Lets say :
first.php
$a = 'blah';
echo 'echo2='.$a;
function foo(){
global $a;
echo 'echo3='.$a;
return $a;
}
second.php
require_once(path/to/the/file/first.php);
echo 'echo='.$a;
$b = foo();
echo 'echo4='.$b;
running the second.php file I get the following output :
echo=blah
echo2=blah
echo3=
echo4=
My question is "why I can't access variable $a in the function foo !
Change $global to global. That should fix it.
http://php.net/manual/en/language.variables.scope.php
or use
$GLOBALS["Your_var_without_dollar_sign"];
http://php.net/manual/en/reserved.variables.globals.php
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;
?>
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.