开发者

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

开发者 https://www.devze.com 2023-02-04 17:00 出处:网络
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

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() {
    //f开发者_JAVA技巧oo
}
?>


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消