2

Possible Duplicate:
Declaring a global variable inside a function

Is it possible to declare variable with global scope from inside a function?

NOTE: I don't want to receive the value of a previously declared variable outside the function. But to have the values of the variables declared inside the function working outside the function scope.

I a way that if I have these variables declared inside a function:

function variables($n){
    $a=1+$n;
    $b="This is number +$n";
}

I could echo them outside the function:

variables(1);
echo $a;
echo '\n';
echo $b;

2
This is number 1

I know I could achieve it returning an array from the function but... I'd like to be sure I could otherwise.

I saw nothing here: http://php.net/manual/en/language.variables.scope.php

Thanks.

Community
  • 1
  • 1
Roger
  • 8,286
  • 17
  • 59
  • 77
  • 1
    If you didn't saw there, you must use the scrollbars on the right of your browser window. Or just use your browsers page-search and search for "global". – hakre Oct 14 '11 at 15:32
  • What about “By declaring $a and $b global within the function, all references to either variable will refer to the global version.”? – Gumbo Oct 14 '11 at 15:32
  • 2
    Global Variables are not good at all.. I highly recommend against even the idea of using them, as it will hit something in your app which you won't anticipate. – Petrogad Oct 14 '11 at 15:33
  • 1
    @Frederico: Don't discriminate global variables, they just do their job ;) – hakre Oct 14 '11 at 15:35
  • Thanks God not everyone "sinks" the "shame" way, I mean: "thinks" the "same" way :-) – Roger Oct 14 '11 at 15:42
  • although yes, you should stay away from global variables, there are places that they help. we have a class that handles our database connection. the class is instantiated to a single var and database is connected to in an auto_prepend file. There are two ways to get the instance into a function to run a query, pass as an argument or use global. I prefer the latter so I don't have to add the instance to every call of the function. Not ideal, but it was setup before I started. – Jonathan Kuhn Oct 14 '11 at 15:46
  • 1
    In a small script this helps to write less code. – Roger Oct 14 '11 at 16:04

1 Answers1

4

You can read elsewhere about why globals are bad, so I'll just stick to the question. You can use the global keyword for this. The same applies if you want to read a global from inside a function.

function variables($n){
    global $a,$b;
    $a=1+$n;
    $b="This is number +$n";
}
grossvogel
  • 6,694
  • 1
  • 25
  • 36
  • Hey!!! it works!!! I thought the global declaration was only to receive variables values from outside of the function scope!!! Thanks!!! – Roger Oct 14 '11 at 15:45
  • 1
    By the way, @grossvogel, thank you for helping me to clarify my doubt without prejudice. Quite different from the "square pins" around. – Roger Oct 14 '11 at 16:09