Casey Flynn
Casey Flynn

Reputation: 14038

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

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
}
?>

Upvotes: 1

Views: 797

Answers (3)

Damp
Damp

Reputation: 3348

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

Upvotes: 2

Ward Bekker
Ward Bekker

Reputation: 6366

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.

Upvotes: 0

kander
kander

Reputation: 4286

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() {} )

Upvotes: 0

Related Questions