Reference: What is variable scope, which variables are accessible from where and what are “undefined...












148















Note: This is a reference question for dealing with variable scope in PHP. Please close any of the many questions fitting this pattern as duplicate of this one.




What is "variable scope" in PHP? Are variables from one .php file accessible in another? Why do I sometimes get "undefined variable" errors?










share|improve this question




















  • 1




    If you titled this as "Undefined variable" you'll get loads more hits :) good job though
    – Dale
    Jun 6 '13 at 10:23












  • @Dale Good point. :)
    – deceze
    Jun 6 '13 at 10:24










  • @Dale, Actually no. 2k views in 2 years is....
    – Pacerier
    Mar 4 '15 at 8:29






  • 6




    @Pacerier ... about the right time to leave a random comment?
    – Dale
    Mar 9 '15 at 13:53










  • @Pacerier I really am not sure either what you're trying to say with that comment though. "Is...." ...what?! :P
    – deceze
    Mar 11 '15 at 8:14
















148















Note: This is a reference question for dealing with variable scope in PHP. Please close any of the many questions fitting this pattern as duplicate of this one.




What is "variable scope" in PHP? Are variables from one .php file accessible in another? Why do I sometimes get "undefined variable" errors?










share|improve this question




















  • 1




    If you titled this as "Undefined variable" you'll get loads more hits :) good job though
    – Dale
    Jun 6 '13 at 10:23












  • @Dale Good point. :)
    – deceze
    Jun 6 '13 at 10:24










  • @Dale, Actually no. 2k views in 2 years is....
    – Pacerier
    Mar 4 '15 at 8:29






  • 6




    @Pacerier ... about the right time to leave a random comment?
    – Dale
    Mar 9 '15 at 13:53










  • @Pacerier I really am not sure either what you're trying to say with that comment though. "Is...." ...what?! :P
    – deceze
    Mar 11 '15 at 8:14














148












148








148


32






Note: This is a reference question for dealing with variable scope in PHP. Please close any of the many questions fitting this pattern as duplicate of this one.




What is "variable scope" in PHP? Are variables from one .php file accessible in another? Why do I sometimes get "undefined variable" errors?










share|improve this question
















Note: This is a reference question for dealing with variable scope in PHP. Please close any of the many questions fitting this pattern as duplicate of this one.




What is "variable scope" in PHP? Are variables from one .php file accessible in another? Why do I sometimes get "undefined variable" errors?







php scope






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 22 '17 at 16:16









Taryn

189k46286351




189k46286351










asked Jun 6 '13 at 10:20









deceze

391k61531687




391k61531687








  • 1




    If you titled this as "Undefined variable" you'll get loads more hits :) good job though
    – Dale
    Jun 6 '13 at 10:23












  • @Dale Good point. :)
    – deceze
    Jun 6 '13 at 10:24










  • @Dale, Actually no. 2k views in 2 years is....
    – Pacerier
    Mar 4 '15 at 8:29






  • 6




    @Pacerier ... about the right time to leave a random comment?
    – Dale
    Mar 9 '15 at 13:53










  • @Pacerier I really am not sure either what you're trying to say with that comment though. "Is...." ...what?! :P
    – deceze
    Mar 11 '15 at 8:14














  • 1




    If you titled this as "Undefined variable" you'll get loads more hits :) good job though
    – Dale
    Jun 6 '13 at 10:23












  • @Dale Good point. :)
    – deceze
    Jun 6 '13 at 10:24










  • @Dale, Actually no. 2k views in 2 years is....
    – Pacerier
    Mar 4 '15 at 8:29






  • 6




    @Pacerier ... about the right time to leave a random comment?
    – Dale
    Mar 9 '15 at 13:53










  • @Pacerier I really am not sure either what you're trying to say with that comment though. "Is...." ...what?! :P
    – deceze
    Mar 11 '15 at 8:14








1




1




If you titled this as "Undefined variable" you'll get loads more hits :) good job though
– Dale
Jun 6 '13 at 10:23






If you titled this as "Undefined variable" you'll get loads more hits :) good job though
– Dale
Jun 6 '13 at 10:23














@Dale Good point. :)
– deceze
Jun 6 '13 at 10:24




@Dale Good point. :)
– deceze
Jun 6 '13 at 10:24












@Dale, Actually no. 2k views in 2 years is....
– Pacerier
Mar 4 '15 at 8:29




@Dale, Actually no. 2k views in 2 years is....
– Pacerier
Mar 4 '15 at 8:29




6




6




@Pacerier ... about the right time to leave a random comment?
– Dale
Mar 9 '15 at 13:53




@Pacerier ... about the right time to leave a random comment?
– Dale
Mar 9 '15 at 13:53












@Pacerier I really am not sure either what you're trying to say with that comment though. "Is...." ...what?! :P
– deceze
Mar 11 '15 at 8:14




@Pacerier I really am not sure either what you're trying to say with that comment though. "Is...." ...what?! :P
– deceze
Mar 11 '15 at 8:14












3 Answers
3






active

oldest

votes


















165














What is "variable scope"?



Variables have a limited "scope", or "places from which they are accessible". Just because you wrote $foo = 'bar'; once somewhere in your application doesn't mean you can refer to $foo from everywhere else inside the application. The variable $foo has a certain scope within which it is valid and only code in the same scope has access to the variable.



How is a scope defined in PHP?



Very simple: PHP has function scope. That's the only kind of scope separator that exists in PHP. Variables inside a function are only available inside that function. Variables outside of functions are available anywhere outside of functions, but not inside any function. This means there's one special scope in PHP: the global scope. Any variable declared outside of any function is within this global scope.



Example:



<?php

$foo = 'bar';

function myFunc() {
$baz = 42;
}


$foo is in the global scope, $baz is in a local scope inside myFunc. Only code inside myFunc has access to $baz. Only code outside myFunc has access to $foo. Neither has access to the other:



<?php

$foo = 'bar';

function myFunc() {
$baz = 42;

echo $foo; // doesn't work
echo $baz; // works
}

echo $foo; // works
echo $baz; // doesn't work


Scope and included files



File boundaries do not separate scope:



a.php



<?php

$foo = 'bar';


b.php



<?php

include 'a.php';

echo $foo; // works!


The same rules apply to included code as applies to any other code: only functions separate scope. For the purpose of scope, you may think of including files like copy and pasting code:



c.php



<?php

function myFunc() {
include 'a.php';

echo $foo; // works
}

myFunc();

echo $foo; // doesn't work!


In the above example, a.php was included inside myFunc, any variables inside a.php only have local function scope. Just because they appear to be in the global scope in a.php doesn't necessarily mean they are, it actually depends on which context that code is included/executed in.



What about functions inside functions and classes?



Every new function declaration introduces a new scope, it's that simple.



(anonymous) functions inside functions



function foo() {
$foo = 'bar';

$bar = function () {
// no access to $foo
$baz = 'baz';
};

// no access to $baz
}


classes



$foo = 'foo';

class Bar {

public function baz() {
// no access to $foo
$baz = 'baz';
}

}

// no access to $baz


What is scope good for?



Dealing with scoping issues may seem annoying, but limited variable scope is essential to writing complex applications! If every variable you declare would be available from everywhere else inside your application, you'd be stepping all over your variables with no real way to track what changes what. There are only so many sensible names you can give to your variables, you probably want to use the variable "$name" in more than one place. If you could only have this unique variable name once in your app, you'd have to resort to really complicated naming schemes to make sure your variables are unique and that you're not changing the wrong variable from the wrong piece of code.



Observe:



function foo() {
echo $bar;
}


If there was no scope, what would the above function do? Where does $bar come from? What state does it have? Is it even initialized? Do you have to check every time? This is not maintainable. Which brings us to...



Crossing scope boundaries



The right way: passing variables in and out



function foo($bar) {
echo $bar;
return 42;
}


The variable $bar is explicitly coming into this scope as function argument. Just looking at this function it's clear where the values it works with originate from. It then explicitly returns a value. The caller has the confidence to know what variables the function will work with and where its return values come from:



$baz   = 'baz';
$blarg = foo($baz);


Extending the scope of variables into anonymous functions



$foo = 'bar';

$baz = function () use ($foo) {
echo $foo;
};

$baz();


The anonymous function explicitly includes $foo from its surrounding scope. Note that this is not the same as global scope.



The wrong way: global



As said before, the global scope is somewhat special, and functions can explicitly import variables from it:



$foo = 'bar';

function baz() {
global $foo;
echo $foo;
$foo = 'baz';
}


This function uses and modifies the global variable $foo. Do not do this! (Unless you really really really really know what you're doing, and even then: don't!)



All the caller of this function sees is this:



baz(); // outputs "bar"
unset($foo);
baz(); // no output, WTF?!
baz(); // outputs "baz", WTF?!?!!


There's no indication that this function has any side effects, yet it does. This very easily becomes a tangled mess as some functions keep modifying and requiring some global state. You want functions to be stateless, acting only on their inputs and returning defined output, however many times you call them.



You should avoid using the global scope in any way as much as possible; most certainly you should not be "pulling" variables out of the global scope into a local scope.






share|improve this answer























  • You just said the wrong way for global, so please tell us when should we use global ? And please explain (a bit) what is static ..?
    – user4920811
    Jun 28 '15 at 10:14












  • @stack There is no "right" way for global. It's always wrong. Passing function parameters is right. static is explained well in the manual and does not have much to do with scope. In a nutshell it can be thought of as a "scoped global variable". I'm expanding a bit on its usage here kunststube.net/static.
    – deceze
    Jun 28 '15 at 12:15












  • My simple thought is if a php variable is important enough to deserve a global status, it deserves a column in a database. Maybe it's an overkill, but it's a fool-proof approach that fits my mediocre programming wit
    – Arthur Tarasov
    Aug 3 '17 at 8:22










  • @Arthur There is so much to unpack there… ಠ_ಠ This is most certainly not an approach I would endorse.
    – deceze
    Aug 3 '17 at 8:24










  • @deceze wee bit of an argument happening here today stackoverflow.com/q/51409392 - where the OP mentions that the duplicate (here) doesn't mention about include_once and possibly require_once should also be added somewhere; just saying. OP voted to reopen their question also. Would their post be a special case and what should be done about it?
    – Funk Forty Niner
    Jul 18 '18 at 19:31





















9














Although variables defined inside of a function's scope can not be accessed from the outside that does not mean you can not use their values after that function completes. PHP has a well known static keyword that is widely used in object-oriented PHP for defining static methods and properties but one should keep in mind that static may also be used inside functions to define static variables.



What is it 'static variable'?



Static variable differs from ordinary variable defined in function's scope in case that it does not loose value when program execution leaves this scope. Let's consider the following example of using static variables:



function countSheep($num) {
static $counter = 0;
$counter += $num;
echo "$counter sheep jumped over fence";
}

countSheep(1);
countSheep(2);
countSheep(3);


Result:



1 sheep jumped over fence
3 sheep jumped over fence
6 sheep jumped over fence


If we'd defined $counter without static then each time echoed value would be the same as $num parameter passed to the function. Using static allows to build this simple counter without additional workaround.



Static variables use-cases




  1. To store values between consequent calls to function.

  2. To store values between recursive calls when there is no way (or no
    purpose) to pass them as params.

  3. To cache value which is normally better to retrieve once. For
    example, result of reading immutable file on server.


Tricks



Static variable exists only in a local function scope. It can not be
accessed outside of the function it has been defined in. So you may
be sure that it will keep its value unchanged until the next call to
that function.



Static variable may only be defined as a scalar or as a scalar
expression (since PHP 5.6). Assigning other values to it inevitably
leads to a failure at least at the moment this article was written.
Nevertheless you are able to do so just on the next line of your code:



function countSheep($num) {
static $counter = 0;
$counter += sqrt($num);//imagine we need to take root of our sheep each time
echo "$counter sheep jumped over fence";
}


Result:



2 sheep jumped over fence
5 sheep jumped over fence
9 sheep jumped over fence


Static function is kinda 'shared' between methods of objects of the
same class. It is easy to understand by viewing the following example:



class SomeClass {
public function foo() {
static $x = 0;
echo ++$x;
}
}

$object1 = new SomeClass;
$object2 = new SomeClass;

$object1->foo(); // 1
$object2->foo(); // 2 oops, $object2 uses the same static $x as $object1
$object1->foo(); // 3 now $object1 increments $x
$object2->foo(); // 4 and now his twin brother


This only works with objects of the same class. If objects are from different classes (even extending one another) behavior of static vars will be as expected.



Is static variable the only way to keep values between calls to a function?



Another way to keep values between function calls is to use closures. Closures were introduced in PHP 5.3. In two words they allow you to limit access to some set of variables within a function scope to another anonymous function that will be the only way to access them. Being in closure variables may imitate (more or less successfully) OOP concepts like 'class constants' (if they were passed in closure by value) or 'private properties' (if passed by reference) in structured programming.



The latter actually allows to use closures instead of static variables. What to use is always up to developer to decide but it should be mentioned that static variables are definitely useful when working with recursions and deserve to be noticed by devs.






share|improve this answer





























    5














    The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. This
    single scope spans included and required files as well. For example:



    <?php
    $a = 1;
    include 'b.inc';
    ?>


    Here the $a variable will be available within the included b.inc script. However, within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope. For example:



    <?php
    $a = 1; /* global scope */

    function test()
    {
    echo $a; /* reference to local scope variable */
    }

    test();
    ?>


    This script will not produce any output because the echo statement refers to a local version of the $a variable, and it has not been assigned a value within this scope. You may notice that this is a little bit different from the C language in that global variables in C are automatically available to functions unless specifically overridden by a local definition. This can cause some problems in that people may inadvertently change a global variable. In PHP global variables must be declared global inside a function if they are going to be used in that function.






    share|improve this answer





















    • It seems a little dishonest to copy verbatim the PHP manual page on variable scope without attribution.
      – bishop
      Oct 29 '18 at 20:02












    protected by Samuel Liew Oct 5 '15 at 9:00



    Thank you for your interest in this question.
    Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



    Would you like to answer one of these unanswered questions instead?














    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    165














    What is "variable scope"?



    Variables have a limited "scope", or "places from which they are accessible". Just because you wrote $foo = 'bar'; once somewhere in your application doesn't mean you can refer to $foo from everywhere else inside the application. The variable $foo has a certain scope within which it is valid and only code in the same scope has access to the variable.



    How is a scope defined in PHP?



    Very simple: PHP has function scope. That's the only kind of scope separator that exists in PHP. Variables inside a function are only available inside that function. Variables outside of functions are available anywhere outside of functions, but not inside any function. This means there's one special scope in PHP: the global scope. Any variable declared outside of any function is within this global scope.



    Example:



    <?php

    $foo = 'bar';

    function myFunc() {
    $baz = 42;
    }


    $foo is in the global scope, $baz is in a local scope inside myFunc. Only code inside myFunc has access to $baz. Only code outside myFunc has access to $foo. Neither has access to the other:



    <?php

    $foo = 'bar';

    function myFunc() {
    $baz = 42;

    echo $foo; // doesn't work
    echo $baz; // works
    }

    echo $foo; // works
    echo $baz; // doesn't work


    Scope and included files



    File boundaries do not separate scope:



    a.php



    <?php

    $foo = 'bar';


    b.php



    <?php

    include 'a.php';

    echo $foo; // works!


    The same rules apply to included code as applies to any other code: only functions separate scope. For the purpose of scope, you may think of including files like copy and pasting code:



    c.php



    <?php

    function myFunc() {
    include 'a.php';

    echo $foo; // works
    }

    myFunc();

    echo $foo; // doesn't work!


    In the above example, a.php was included inside myFunc, any variables inside a.php only have local function scope. Just because they appear to be in the global scope in a.php doesn't necessarily mean they are, it actually depends on which context that code is included/executed in.



    What about functions inside functions and classes?



    Every new function declaration introduces a new scope, it's that simple.



    (anonymous) functions inside functions



    function foo() {
    $foo = 'bar';

    $bar = function () {
    // no access to $foo
    $baz = 'baz';
    };

    // no access to $baz
    }


    classes



    $foo = 'foo';

    class Bar {

    public function baz() {
    // no access to $foo
    $baz = 'baz';
    }

    }

    // no access to $baz


    What is scope good for?



    Dealing with scoping issues may seem annoying, but limited variable scope is essential to writing complex applications! If every variable you declare would be available from everywhere else inside your application, you'd be stepping all over your variables with no real way to track what changes what. There are only so many sensible names you can give to your variables, you probably want to use the variable "$name" in more than one place. If you could only have this unique variable name once in your app, you'd have to resort to really complicated naming schemes to make sure your variables are unique and that you're not changing the wrong variable from the wrong piece of code.



    Observe:



    function foo() {
    echo $bar;
    }


    If there was no scope, what would the above function do? Where does $bar come from? What state does it have? Is it even initialized? Do you have to check every time? This is not maintainable. Which brings us to...



    Crossing scope boundaries



    The right way: passing variables in and out



    function foo($bar) {
    echo $bar;
    return 42;
    }


    The variable $bar is explicitly coming into this scope as function argument. Just looking at this function it's clear where the values it works with originate from. It then explicitly returns a value. The caller has the confidence to know what variables the function will work with and where its return values come from:



    $baz   = 'baz';
    $blarg = foo($baz);


    Extending the scope of variables into anonymous functions



    $foo = 'bar';

    $baz = function () use ($foo) {
    echo $foo;
    };

    $baz();


    The anonymous function explicitly includes $foo from its surrounding scope. Note that this is not the same as global scope.



    The wrong way: global



    As said before, the global scope is somewhat special, and functions can explicitly import variables from it:



    $foo = 'bar';

    function baz() {
    global $foo;
    echo $foo;
    $foo = 'baz';
    }


    This function uses and modifies the global variable $foo. Do not do this! (Unless you really really really really know what you're doing, and even then: don't!)



    All the caller of this function sees is this:



    baz(); // outputs "bar"
    unset($foo);
    baz(); // no output, WTF?!
    baz(); // outputs "baz", WTF?!?!!


    There's no indication that this function has any side effects, yet it does. This very easily becomes a tangled mess as some functions keep modifying and requiring some global state. You want functions to be stateless, acting only on their inputs and returning defined output, however many times you call them.



    You should avoid using the global scope in any way as much as possible; most certainly you should not be "pulling" variables out of the global scope into a local scope.






    share|improve this answer























    • You just said the wrong way for global, so please tell us when should we use global ? And please explain (a bit) what is static ..?
      – user4920811
      Jun 28 '15 at 10:14












    • @stack There is no "right" way for global. It's always wrong. Passing function parameters is right. static is explained well in the manual and does not have much to do with scope. In a nutshell it can be thought of as a "scoped global variable". I'm expanding a bit on its usage here kunststube.net/static.
      – deceze
      Jun 28 '15 at 12:15












    • My simple thought is if a php variable is important enough to deserve a global status, it deserves a column in a database. Maybe it's an overkill, but it's a fool-proof approach that fits my mediocre programming wit
      – Arthur Tarasov
      Aug 3 '17 at 8:22










    • @Arthur There is so much to unpack there… ಠ_ಠ This is most certainly not an approach I would endorse.
      – deceze
      Aug 3 '17 at 8:24










    • @deceze wee bit of an argument happening here today stackoverflow.com/q/51409392 - where the OP mentions that the duplicate (here) doesn't mention about include_once and possibly require_once should also be added somewhere; just saying. OP voted to reopen their question also. Would their post be a special case and what should be done about it?
      – Funk Forty Niner
      Jul 18 '18 at 19:31


















    165














    What is "variable scope"?



    Variables have a limited "scope", or "places from which they are accessible". Just because you wrote $foo = 'bar'; once somewhere in your application doesn't mean you can refer to $foo from everywhere else inside the application. The variable $foo has a certain scope within which it is valid and only code in the same scope has access to the variable.



    How is a scope defined in PHP?



    Very simple: PHP has function scope. That's the only kind of scope separator that exists in PHP. Variables inside a function are only available inside that function. Variables outside of functions are available anywhere outside of functions, but not inside any function. This means there's one special scope in PHP: the global scope. Any variable declared outside of any function is within this global scope.



    Example:



    <?php

    $foo = 'bar';

    function myFunc() {
    $baz = 42;
    }


    $foo is in the global scope, $baz is in a local scope inside myFunc. Only code inside myFunc has access to $baz. Only code outside myFunc has access to $foo. Neither has access to the other:



    <?php

    $foo = 'bar';

    function myFunc() {
    $baz = 42;

    echo $foo; // doesn't work
    echo $baz; // works
    }

    echo $foo; // works
    echo $baz; // doesn't work


    Scope and included files



    File boundaries do not separate scope:



    a.php



    <?php

    $foo = 'bar';


    b.php



    <?php

    include 'a.php';

    echo $foo; // works!


    The same rules apply to included code as applies to any other code: only functions separate scope. For the purpose of scope, you may think of including files like copy and pasting code:



    c.php



    <?php

    function myFunc() {
    include 'a.php';

    echo $foo; // works
    }

    myFunc();

    echo $foo; // doesn't work!


    In the above example, a.php was included inside myFunc, any variables inside a.php only have local function scope. Just because they appear to be in the global scope in a.php doesn't necessarily mean they are, it actually depends on which context that code is included/executed in.



    What about functions inside functions and classes?



    Every new function declaration introduces a new scope, it's that simple.



    (anonymous) functions inside functions



    function foo() {
    $foo = 'bar';

    $bar = function () {
    // no access to $foo
    $baz = 'baz';
    };

    // no access to $baz
    }


    classes



    $foo = 'foo';

    class Bar {

    public function baz() {
    // no access to $foo
    $baz = 'baz';
    }

    }

    // no access to $baz


    What is scope good for?



    Dealing with scoping issues may seem annoying, but limited variable scope is essential to writing complex applications! If every variable you declare would be available from everywhere else inside your application, you'd be stepping all over your variables with no real way to track what changes what. There are only so many sensible names you can give to your variables, you probably want to use the variable "$name" in more than one place. If you could only have this unique variable name once in your app, you'd have to resort to really complicated naming schemes to make sure your variables are unique and that you're not changing the wrong variable from the wrong piece of code.



    Observe:



    function foo() {
    echo $bar;
    }


    If there was no scope, what would the above function do? Where does $bar come from? What state does it have? Is it even initialized? Do you have to check every time? This is not maintainable. Which brings us to...



    Crossing scope boundaries



    The right way: passing variables in and out



    function foo($bar) {
    echo $bar;
    return 42;
    }


    The variable $bar is explicitly coming into this scope as function argument. Just looking at this function it's clear where the values it works with originate from. It then explicitly returns a value. The caller has the confidence to know what variables the function will work with and where its return values come from:



    $baz   = 'baz';
    $blarg = foo($baz);


    Extending the scope of variables into anonymous functions



    $foo = 'bar';

    $baz = function () use ($foo) {
    echo $foo;
    };

    $baz();


    The anonymous function explicitly includes $foo from its surrounding scope. Note that this is not the same as global scope.



    The wrong way: global



    As said before, the global scope is somewhat special, and functions can explicitly import variables from it:



    $foo = 'bar';

    function baz() {
    global $foo;
    echo $foo;
    $foo = 'baz';
    }


    This function uses and modifies the global variable $foo. Do not do this! (Unless you really really really really know what you're doing, and even then: don't!)



    All the caller of this function sees is this:



    baz(); // outputs "bar"
    unset($foo);
    baz(); // no output, WTF?!
    baz(); // outputs "baz", WTF?!?!!


    There's no indication that this function has any side effects, yet it does. This very easily becomes a tangled mess as some functions keep modifying and requiring some global state. You want functions to be stateless, acting only on their inputs and returning defined output, however many times you call them.



    You should avoid using the global scope in any way as much as possible; most certainly you should not be "pulling" variables out of the global scope into a local scope.






    share|improve this answer























    • You just said the wrong way for global, so please tell us when should we use global ? And please explain (a bit) what is static ..?
      – user4920811
      Jun 28 '15 at 10:14












    • @stack There is no "right" way for global. It's always wrong. Passing function parameters is right. static is explained well in the manual and does not have much to do with scope. In a nutshell it can be thought of as a "scoped global variable". I'm expanding a bit on its usage here kunststube.net/static.
      – deceze
      Jun 28 '15 at 12:15












    • My simple thought is if a php variable is important enough to deserve a global status, it deserves a column in a database. Maybe it's an overkill, but it's a fool-proof approach that fits my mediocre programming wit
      – Arthur Tarasov
      Aug 3 '17 at 8:22










    • @Arthur There is so much to unpack there… ಠ_ಠ This is most certainly not an approach I would endorse.
      – deceze
      Aug 3 '17 at 8:24










    • @deceze wee bit of an argument happening here today stackoverflow.com/q/51409392 - where the OP mentions that the duplicate (here) doesn't mention about include_once and possibly require_once should also be added somewhere; just saying. OP voted to reopen their question also. Would their post be a special case and what should be done about it?
      – Funk Forty Niner
      Jul 18 '18 at 19:31
















    165












    165








    165






    What is "variable scope"?



    Variables have a limited "scope", or "places from which they are accessible". Just because you wrote $foo = 'bar'; once somewhere in your application doesn't mean you can refer to $foo from everywhere else inside the application. The variable $foo has a certain scope within which it is valid and only code in the same scope has access to the variable.



    How is a scope defined in PHP?



    Very simple: PHP has function scope. That's the only kind of scope separator that exists in PHP. Variables inside a function are only available inside that function. Variables outside of functions are available anywhere outside of functions, but not inside any function. This means there's one special scope in PHP: the global scope. Any variable declared outside of any function is within this global scope.



    Example:



    <?php

    $foo = 'bar';

    function myFunc() {
    $baz = 42;
    }


    $foo is in the global scope, $baz is in a local scope inside myFunc. Only code inside myFunc has access to $baz. Only code outside myFunc has access to $foo. Neither has access to the other:



    <?php

    $foo = 'bar';

    function myFunc() {
    $baz = 42;

    echo $foo; // doesn't work
    echo $baz; // works
    }

    echo $foo; // works
    echo $baz; // doesn't work


    Scope and included files



    File boundaries do not separate scope:



    a.php



    <?php

    $foo = 'bar';


    b.php



    <?php

    include 'a.php';

    echo $foo; // works!


    The same rules apply to included code as applies to any other code: only functions separate scope. For the purpose of scope, you may think of including files like copy and pasting code:



    c.php



    <?php

    function myFunc() {
    include 'a.php';

    echo $foo; // works
    }

    myFunc();

    echo $foo; // doesn't work!


    In the above example, a.php was included inside myFunc, any variables inside a.php only have local function scope. Just because they appear to be in the global scope in a.php doesn't necessarily mean they are, it actually depends on which context that code is included/executed in.



    What about functions inside functions and classes?



    Every new function declaration introduces a new scope, it's that simple.



    (anonymous) functions inside functions



    function foo() {
    $foo = 'bar';

    $bar = function () {
    // no access to $foo
    $baz = 'baz';
    };

    // no access to $baz
    }


    classes



    $foo = 'foo';

    class Bar {

    public function baz() {
    // no access to $foo
    $baz = 'baz';
    }

    }

    // no access to $baz


    What is scope good for?



    Dealing with scoping issues may seem annoying, but limited variable scope is essential to writing complex applications! If every variable you declare would be available from everywhere else inside your application, you'd be stepping all over your variables with no real way to track what changes what. There are only so many sensible names you can give to your variables, you probably want to use the variable "$name" in more than one place. If you could only have this unique variable name once in your app, you'd have to resort to really complicated naming schemes to make sure your variables are unique and that you're not changing the wrong variable from the wrong piece of code.



    Observe:



    function foo() {
    echo $bar;
    }


    If there was no scope, what would the above function do? Where does $bar come from? What state does it have? Is it even initialized? Do you have to check every time? This is not maintainable. Which brings us to...



    Crossing scope boundaries



    The right way: passing variables in and out



    function foo($bar) {
    echo $bar;
    return 42;
    }


    The variable $bar is explicitly coming into this scope as function argument. Just looking at this function it's clear where the values it works with originate from. It then explicitly returns a value. The caller has the confidence to know what variables the function will work with and where its return values come from:



    $baz   = 'baz';
    $blarg = foo($baz);


    Extending the scope of variables into anonymous functions



    $foo = 'bar';

    $baz = function () use ($foo) {
    echo $foo;
    };

    $baz();


    The anonymous function explicitly includes $foo from its surrounding scope. Note that this is not the same as global scope.



    The wrong way: global



    As said before, the global scope is somewhat special, and functions can explicitly import variables from it:



    $foo = 'bar';

    function baz() {
    global $foo;
    echo $foo;
    $foo = 'baz';
    }


    This function uses and modifies the global variable $foo. Do not do this! (Unless you really really really really know what you're doing, and even then: don't!)



    All the caller of this function sees is this:



    baz(); // outputs "bar"
    unset($foo);
    baz(); // no output, WTF?!
    baz(); // outputs "baz", WTF?!?!!


    There's no indication that this function has any side effects, yet it does. This very easily becomes a tangled mess as some functions keep modifying and requiring some global state. You want functions to be stateless, acting only on their inputs and returning defined output, however many times you call them.



    You should avoid using the global scope in any way as much as possible; most certainly you should not be "pulling" variables out of the global scope into a local scope.






    share|improve this answer














    What is "variable scope"?



    Variables have a limited "scope", or "places from which they are accessible". Just because you wrote $foo = 'bar'; once somewhere in your application doesn't mean you can refer to $foo from everywhere else inside the application. The variable $foo has a certain scope within which it is valid and only code in the same scope has access to the variable.



    How is a scope defined in PHP?



    Very simple: PHP has function scope. That's the only kind of scope separator that exists in PHP. Variables inside a function are only available inside that function. Variables outside of functions are available anywhere outside of functions, but not inside any function. This means there's one special scope in PHP: the global scope. Any variable declared outside of any function is within this global scope.



    Example:



    <?php

    $foo = 'bar';

    function myFunc() {
    $baz = 42;
    }


    $foo is in the global scope, $baz is in a local scope inside myFunc. Only code inside myFunc has access to $baz. Only code outside myFunc has access to $foo. Neither has access to the other:



    <?php

    $foo = 'bar';

    function myFunc() {
    $baz = 42;

    echo $foo; // doesn't work
    echo $baz; // works
    }

    echo $foo; // works
    echo $baz; // doesn't work


    Scope and included files



    File boundaries do not separate scope:



    a.php



    <?php

    $foo = 'bar';


    b.php



    <?php

    include 'a.php';

    echo $foo; // works!


    The same rules apply to included code as applies to any other code: only functions separate scope. For the purpose of scope, you may think of including files like copy and pasting code:



    c.php



    <?php

    function myFunc() {
    include 'a.php';

    echo $foo; // works
    }

    myFunc();

    echo $foo; // doesn't work!


    In the above example, a.php was included inside myFunc, any variables inside a.php only have local function scope. Just because they appear to be in the global scope in a.php doesn't necessarily mean they are, it actually depends on which context that code is included/executed in.



    What about functions inside functions and classes?



    Every new function declaration introduces a new scope, it's that simple.



    (anonymous) functions inside functions



    function foo() {
    $foo = 'bar';

    $bar = function () {
    // no access to $foo
    $baz = 'baz';
    };

    // no access to $baz
    }


    classes



    $foo = 'foo';

    class Bar {

    public function baz() {
    // no access to $foo
    $baz = 'baz';
    }

    }

    // no access to $baz


    What is scope good for?



    Dealing with scoping issues may seem annoying, but limited variable scope is essential to writing complex applications! If every variable you declare would be available from everywhere else inside your application, you'd be stepping all over your variables with no real way to track what changes what. There are only so many sensible names you can give to your variables, you probably want to use the variable "$name" in more than one place. If you could only have this unique variable name once in your app, you'd have to resort to really complicated naming schemes to make sure your variables are unique and that you're not changing the wrong variable from the wrong piece of code.



    Observe:



    function foo() {
    echo $bar;
    }


    If there was no scope, what would the above function do? Where does $bar come from? What state does it have? Is it even initialized? Do you have to check every time? This is not maintainable. Which brings us to...



    Crossing scope boundaries



    The right way: passing variables in and out



    function foo($bar) {
    echo $bar;
    return 42;
    }


    The variable $bar is explicitly coming into this scope as function argument. Just looking at this function it's clear where the values it works with originate from. It then explicitly returns a value. The caller has the confidence to know what variables the function will work with and where its return values come from:



    $baz   = 'baz';
    $blarg = foo($baz);


    Extending the scope of variables into anonymous functions



    $foo = 'bar';

    $baz = function () use ($foo) {
    echo $foo;
    };

    $baz();


    The anonymous function explicitly includes $foo from its surrounding scope. Note that this is not the same as global scope.



    The wrong way: global



    As said before, the global scope is somewhat special, and functions can explicitly import variables from it:



    $foo = 'bar';

    function baz() {
    global $foo;
    echo $foo;
    $foo = 'baz';
    }


    This function uses and modifies the global variable $foo. Do not do this! (Unless you really really really really know what you're doing, and even then: don't!)



    All the caller of this function sees is this:



    baz(); // outputs "bar"
    unset($foo);
    baz(); // no output, WTF?!
    baz(); // outputs "baz", WTF?!?!!


    There's no indication that this function has any side effects, yet it does. This very easily becomes a tangled mess as some functions keep modifying and requiring some global state. You want functions to be stateless, acting only on their inputs and returning defined output, however many times you call them.



    You should avoid using the global scope in any way as much as possible; most certainly you should not be "pulling" variables out of the global scope into a local scope.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Mar 1 '18 at 6:40

























    answered Jun 6 '13 at 10:20









    deceze

    391k61531687




    391k61531687












    • You just said the wrong way for global, so please tell us when should we use global ? And please explain (a bit) what is static ..?
      – user4920811
      Jun 28 '15 at 10:14












    • @stack There is no "right" way for global. It's always wrong. Passing function parameters is right. static is explained well in the manual and does not have much to do with scope. In a nutshell it can be thought of as a "scoped global variable". I'm expanding a bit on its usage here kunststube.net/static.
      – deceze
      Jun 28 '15 at 12:15












    • My simple thought is if a php variable is important enough to deserve a global status, it deserves a column in a database. Maybe it's an overkill, but it's a fool-proof approach that fits my mediocre programming wit
      – Arthur Tarasov
      Aug 3 '17 at 8:22










    • @Arthur There is so much to unpack there… ಠ_ಠ This is most certainly not an approach I would endorse.
      – deceze
      Aug 3 '17 at 8:24










    • @deceze wee bit of an argument happening here today stackoverflow.com/q/51409392 - where the OP mentions that the duplicate (here) doesn't mention about include_once and possibly require_once should also be added somewhere; just saying. OP voted to reopen their question also. Would their post be a special case and what should be done about it?
      – Funk Forty Niner
      Jul 18 '18 at 19:31




















    • You just said the wrong way for global, so please tell us when should we use global ? And please explain (a bit) what is static ..?
      – user4920811
      Jun 28 '15 at 10:14












    • @stack There is no "right" way for global. It's always wrong. Passing function parameters is right. static is explained well in the manual and does not have much to do with scope. In a nutshell it can be thought of as a "scoped global variable". I'm expanding a bit on its usage here kunststube.net/static.
      – deceze
      Jun 28 '15 at 12:15












    • My simple thought is if a php variable is important enough to deserve a global status, it deserves a column in a database. Maybe it's an overkill, but it's a fool-proof approach that fits my mediocre programming wit
      – Arthur Tarasov
      Aug 3 '17 at 8:22










    • @Arthur There is so much to unpack there… ಠ_ಠ This is most certainly not an approach I would endorse.
      – deceze
      Aug 3 '17 at 8:24










    • @deceze wee bit of an argument happening here today stackoverflow.com/q/51409392 - where the OP mentions that the duplicate (here) doesn't mention about include_once and possibly require_once should also be added somewhere; just saying. OP voted to reopen their question also. Would their post be a special case and what should be done about it?
      – Funk Forty Niner
      Jul 18 '18 at 19:31


















    You just said the wrong way for global, so please tell us when should we use global ? And please explain (a bit) what is static ..?
    – user4920811
    Jun 28 '15 at 10:14






    You just said the wrong way for global, so please tell us when should we use global ? And please explain (a bit) what is static ..?
    – user4920811
    Jun 28 '15 at 10:14














    @stack There is no "right" way for global. It's always wrong. Passing function parameters is right. static is explained well in the manual and does not have much to do with scope. In a nutshell it can be thought of as a "scoped global variable". I'm expanding a bit on its usage here kunststube.net/static.
    – deceze
    Jun 28 '15 at 12:15






    @stack There is no "right" way for global. It's always wrong. Passing function parameters is right. static is explained well in the manual and does not have much to do with scope. In a nutshell it can be thought of as a "scoped global variable". I'm expanding a bit on its usage here kunststube.net/static.
    – deceze
    Jun 28 '15 at 12:15














    My simple thought is if a php variable is important enough to deserve a global status, it deserves a column in a database. Maybe it's an overkill, but it's a fool-proof approach that fits my mediocre programming wit
    – Arthur Tarasov
    Aug 3 '17 at 8:22




    My simple thought is if a php variable is important enough to deserve a global status, it deserves a column in a database. Maybe it's an overkill, but it's a fool-proof approach that fits my mediocre programming wit
    – Arthur Tarasov
    Aug 3 '17 at 8:22












    @Arthur There is so much to unpack there… ಠ_ಠ This is most certainly not an approach I would endorse.
    – deceze
    Aug 3 '17 at 8:24




    @Arthur There is so much to unpack there… ಠ_ಠ This is most certainly not an approach I would endorse.
    – deceze
    Aug 3 '17 at 8:24












    @deceze wee bit of an argument happening here today stackoverflow.com/q/51409392 - where the OP mentions that the duplicate (here) doesn't mention about include_once and possibly require_once should also be added somewhere; just saying. OP voted to reopen their question also. Would their post be a special case and what should be done about it?
    – Funk Forty Niner
    Jul 18 '18 at 19:31






    @deceze wee bit of an argument happening here today stackoverflow.com/q/51409392 - where the OP mentions that the duplicate (here) doesn't mention about include_once and possibly require_once should also be added somewhere; just saying. OP voted to reopen their question also. Would their post be a special case and what should be done about it?
    – Funk Forty Niner
    Jul 18 '18 at 19:31















    9














    Although variables defined inside of a function's scope can not be accessed from the outside that does not mean you can not use their values after that function completes. PHP has a well known static keyword that is widely used in object-oriented PHP for defining static methods and properties but one should keep in mind that static may also be used inside functions to define static variables.



    What is it 'static variable'?



    Static variable differs from ordinary variable defined in function's scope in case that it does not loose value when program execution leaves this scope. Let's consider the following example of using static variables:



    function countSheep($num) {
    static $counter = 0;
    $counter += $num;
    echo "$counter sheep jumped over fence";
    }

    countSheep(1);
    countSheep(2);
    countSheep(3);


    Result:



    1 sheep jumped over fence
    3 sheep jumped over fence
    6 sheep jumped over fence


    If we'd defined $counter without static then each time echoed value would be the same as $num parameter passed to the function. Using static allows to build this simple counter without additional workaround.



    Static variables use-cases




    1. To store values between consequent calls to function.

    2. To store values between recursive calls when there is no way (or no
      purpose) to pass them as params.

    3. To cache value which is normally better to retrieve once. For
      example, result of reading immutable file on server.


    Tricks



    Static variable exists only in a local function scope. It can not be
    accessed outside of the function it has been defined in. So you may
    be sure that it will keep its value unchanged until the next call to
    that function.



    Static variable may only be defined as a scalar or as a scalar
    expression (since PHP 5.6). Assigning other values to it inevitably
    leads to a failure at least at the moment this article was written.
    Nevertheless you are able to do so just on the next line of your code:



    function countSheep($num) {
    static $counter = 0;
    $counter += sqrt($num);//imagine we need to take root of our sheep each time
    echo "$counter sheep jumped over fence";
    }


    Result:



    2 sheep jumped over fence
    5 sheep jumped over fence
    9 sheep jumped over fence


    Static function is kinda 'shared' between methods of objects of the
    same class. It is easy to understand by viewing the following example:



    class SomeClass {
    public function foo() {
    static $x = 0;
    echo ++$x;
    }
    }

    $object1 = new SomeClass;
    $object2 = new SomeClass;

    $object1->foo(); // 1
    $object2->foo(); // 2 oops, $object2 uses the same static $x as $object1
    $object1->foo(); // 3 now $object1 increments $x
    $object2->foo(); // 4 and now his twin brother


    This only works with objects of the same class. If objects are from different classes (even extending one another) behavior of static vars will be as expected.



    Is static variable the only way to keep values between calls to a function?



    Another way to keep values between function calls is to use closures. Closures were introduced in PHP 5.3. In two words they allow you to limit access to some set of variables within a function scope to another anonymous function that will be the only way to access them. Being in closure variables may imitate (more or less successfully) OOP concepts like 'class constants' (if they were passed in closure by value) or 'private properties' (if passed by reference) in structured programming.



    The latter actually allows to use closures instead of static variables. What to use is always up to developer to decide but it should be mentioned that static variables are definitely useful when working with recursions and deserve to be noticed by devs.






    share|improve this answer


























      9














      Although variables defined inside of a function's scope can not be accessed from the outside that does not mean you can not use their values after that function completes. PHP has a well known static keyword that is widely used in object-oriented PHP for defining static methods and properties but one should keep in mind that static may also be used inside functions to define static variables.



      What is it 'static variable'?



      Static variable differs from ordinary variable defined in function's scope in case that it does not loose value when program execution leaves this scope. Let's consider the following example of using static variables:



      function countSheep($num) {
      static $counter = 0;
      $counter += $num;
      echo "$counter sheep jumped over fence";
      }

      countSheep(1);
      countSheep(2);
      countSheep(3);


      Result:



      1 sheep jumped over fence
      3 sheep jumped over fence
      6 sheep jumped over fence


      If we'd defined $counter without static then each time echoed value would be the same as $num parameter passed to the function. Using static allows to build this simple counter without additional workaround.



      Static variables use-cases




      1. To store values between consequent calls to function.

      2. To store values between recursive calls when there is no way (or no
        purpose) to pass them as params.

      3. To cache value which is normally better to retrieve once. For
        example, result of reading immutable file on server.


      Tricks



      Static variable exists only in a local function scope. It can not be
      accessed outside of the function it has been defined in. So you may
      be sure that it will keep its value unchanged until the next call to
      that function.



      Static variable may only be defined as a scalar or as a scalar
      expression (since PHP 5.6). Assigning other values to it inevitably
      leads to a failure at least at the moment this article was written.
      Nevertheless you are able to do so just on the next line of your code:



      function countSheep($num) {
      static $counter = 0;
      $counter += sqrt($num);//imagine we need to take root of our sheep each time
      echo "$counter sheep jumped over fence";
      }


      Result:



      2 sheep jumped over fence
      5 sheep jumped over fence
      9 sheep jumped over fence


      Static function is kinda 'shared' between methods of objects of the
      same class. It is easy to understand by viewing the following example:



      class SomeClass {
      public function foo() {
      static $x = 0;
      echo ++$x;
      }
      }

      $object1 = new SomeClass;
      $object2 = new SomeClass;

      $object1->foo(); // 1
      $object2->foo(); // 2 oops, $object2 uses the same static $x as $object1
      $object1->foo(); // 3 now $object1 increments $x
      $object2->foo(); // 4 and now his twin brother


      This only works with objects of the same class. If objects are from different classes (even extending one another) behavior of static vars will be as expected.



      Is static variable the only way to keep values between calls to a function?



      Another way to keep values between function calls is to use closures. Closures were introduced in PHP 5.3. In two words they allow you to limit access to some set of variables within a function scope to another anonymous function that will be the only way to access them. Being in closure variables may imitate (more or less successfully) OOP concepts like 'class constants' (if they were passed in closure by value) or 'private properties' (if passed by reference) in structured programming.



      The latter actually allows to use closures instead of static variables. What to use is always up to developer to decide but it should be mentioned that static variables are definitely useful when working with recursions and deserve to be noticed by devs.






      share|improve this answer
























        9












        9








        9






        Although variables defined inside of a function's scope can not be accessed from the outside that does not mean you can not use their values after that function completes. PHP has a well known static keyword that is widely used in object-oriented PHP for defining static methods and properties but one should keep in mind that static may also be used inside functions to define static variables.



        What is it 'static variable'?



        Static variable differs from ordinary variable defined in function's scope in case that it does not loose value when program execution leaves this scope. Let's consider the following example of using static variables:



        function countSheep($num) {
        static $counter = 0;
        $counter += $num;
        echo "$counter sheep jumped over fence";
        }

        countSheep(1);
        countSheep(2);
        countSheep(3);


        Result:



        1 sheep jumped over fence
        3 sheep jumped over fence
        6 sheep jumped over fence


        If we'd defined $counter without static then each time echoed value would be the same as $num parameter passed to the function. Using static allows to build this simple counter without additional workaround.



        Static variables use-cases




        1. To store values between consequent calls to function.

        2. To store values between recursive calls when there is no way (or no
          purpose) to pass them as params.

        3. To cache value which is normally better to retrieve once. For
          example, result of reading immutable file on server.


        Tricks



        Static variable exists only in a local function scope. It can not be
        accessed outside of the function it has been defined in. So you may
        be sure that it will keep its value unchanged until the next call to
        that function.



        Static variable may only be defined as a scalar or as a scalar
        expression (since PHP 5.6). Assigning other values to it inevitably
        leads to a failure at least at the moment this article was written.
        Nevertheless you are able to do so just on the next line of your code:



        function countSheep($num) {
        static $counter = 0;
        $counter += sqrt($num);//imagine we need to take root of our sheep each time
        echo "$counter sheep jumped over fence";
        }


        Result:



        2 sheep jumped over fence
        5 sheep jumped over fence
        9 sheep jumped over fence


        Static function is kinda 'shared' between methods of objects of the
        same class. It is easy to understand by viewing the following example:



        class SomeClass {
        public function foo() {
        static $x = 0;
        echo ++$x;
        }
        }

        $object1 = new SomeClass;
        $object2 = new SomeClass;

        $object1->foo(); // 1
        $object2->foo(); // 2 oops, $object2 uses the same static $x as $object1
        $object1->foo(); // 3 now $object1 increments $x
        $object2->foo(); // 4 and now his twin brother


        This only works with objects of the same class. If objects are from different classes (even extending one another) behavior of static vars will be as expected.



        Is static variable the only way to keep values between calls to a function?



        Another way to keep values between function calls is to use closures. Closures were introduced in PHP 5.3. In two words they allow you to limit access to some set of variables within a function scope to another anonymous function that will be the only way to access them. Being in closure variables may imitate (more or less successfully) OOP concepts like 'class constants' (if they were passed in closure by value) or 'private properties' (if passed by reference) in structured programming.



        The latter actually allows to use closures instead of static variables. What to use is always up to developer to decide but it should be mentioned that static variables are definitely useful when working with recursions and deserve to be noticed by devs.






        share|improve this answer












        Although variables defined inside of a function's scope can not be accessed from the outside that does not mean you can not use their values after that function completes. PHP has a well known static keyword that is widely used in object-oriented PHP for defining static methods and properties but one should keep in mind that static may also be used inside functions to define static variables.



        What is it 'static variable'?



        Static variable differs from ordinary variable defined in function's scope in case that it does not loose value when program execution leaves this scope. Let's consider the following example of using static variables:



        function countSheep($num) {
        static $counter = 0;
        $counter += $num;
        echo "$counter sheep jumped over fence";
        }

        countSheep(1);
        countSheep(2);
        countSheep(3);


        Result:



        1 sheep jumped over fence
        3 sheep jumped over fence
        6 sheep jumped over fence


        If we'd defined $counter without static then each time echoed value would be the same as $num parameter passed to the function. Using static allows to build this simple counter without additional workaround.



        Static variables use-cases




        1. To store values between consequent calls to function.

        2. To store values between recursive calls when there is no way (or no
          purpose) to pass them as params.

        3. To cache value which is normally better to retrieve once. For
          example, result of reading immutable file on server.


        Tricks



        Static variable exists only in a local function scope. It can not be
        accessed outside of the function it has been defined in. So you may
        be sure that it will keep its value unchanged until the next call to
        that function.



        Static variable may only be defined as a scalar or as a scalar
        expression (since PHP 5.6). Assigning other values to it inevitably
        leads to a failure at least at the moment this article was written.
        Nevertheless you are able to do so just on the next line of your code:



        function countSheep($num) {
        static $counter = 0;
        $counter += sqrt($num);//imagine we need to take root of our sheep each time
        echo "$counter sheep jumped over fence";
        }


        Result:



        2 sheep jumped over fence
        5 sheep jumped over fence
        9 sheep jumped over fence


        Static function is kinda 'shared' between methods of objects of the
        same class. It is easy to understand by viewing the following example:



        class SomeClass {
        public function foo() {
        static $x = 0;
        echo ++$x;
        }
        }

        $object1 = new SomeClass;
        $object2 = new SomeClass;

        $object1->foo(); // 1
        $object2->foo(); // 2 oops, $object2 uses the same static $x as $object1
        $object1->foo(); // 3 now $object1 increments $x
        $object2->foo(); // 4 and now his twin brother


        This only works with objects of the same class. If objects are from different classes (even extending one another) behavior of static vars will be as expected.



        Is static variable the only way to keep values between calls to a function?



        Another way to keep values between function calls is to use closures. Closures were introduced in PHP 5.3. In two words they allow you to limit access to some set of variables within a function scope to another anonymous function that will be the only way to access them. Being in closure variables may imitate (more or less successfully) OOP concepts like 'class constants' (if they were passed in closure by value) or 'private properties' (if passed by reference) in structured programming.



        The latter actually allows to use closures instead of static variables. What to use is always up to developer to decide but it should be mentioned that static variables are definitely useful when working with recursions and deserve to be noticed by devs.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Feb 16 '17 at 21:06









        alex_edev

        367412




        367412























            5














            The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. This
            single scope spans included and required files as well. For example:



            <?php
            $a = 1;
            include 'b.inc';
            ?>


            Here the $a variable will be available within the included b.inc script. However, within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope. For example:



            <?php
            $a = 1; /* global scope */

            function test()
            {
            echo $a; /* reference to local scope variable */
            }

            test();
            ?>


            This script will not produce any output because the echo statement refers to a local version of the $a variable, and it has not been assigned a value within this scope. You may notice that this is a little bit different from the C language in that global variables in C are automatically available to functions unless specifically overridden by a local definition. This can cause some problems in that people may inadvertently change a global variable. In PHP global variables must be declared global inside a function if they are going to be used in that function.






            share|improve this answer





















            • It seems a little dishonest to copy verbatim the PHP manual page on variable scope without attribution.
              – bishop
              Oct 29 '18 at 20:02


















            5














            The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. This
            single scope spans included and required files as well. For example:



            <?php
            $a = 1;
            include 'b.inc';
            ?>


            Here the $a variable will be available within the included b.inc script. However, within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope. For example:



            <?php
            $a = 1; /* global scope */

            function test()
            {
            echo $a; /* reference to local scope variable */
            }

            test();
            ?>


            This script will not produce any output because the echo statement refers to a local version of the $a variable, and it has not been assigned a value within this scope. You may notice that this is a little bit different from the C language in that global variables in C are automatically available to functions unless specifically overridden by a local definition. This can cause some problems in that people may inadvertently change a global variable. In PHP global variables must be declared global inside a function if they are going to be used in that function.






            share|improve this answer





















            • It seems a little dishonest to copy verbatim the PHP manual page on variable scope without attribution.
              – bishop
              Oct 29 '18 at 20:02
















            5












            5








            5






            The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. This
            single scope spans included and required files as well. For example:



            <?php
            $a = 1;
            include 'b.inc';
            ?>


            Here the $a variable will be available within the included b.inc script. However, within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope. For example:



            <?php
            $a = 1; /* global scope */

            function test()
            {
            echo $a; /* reference to local scope variable */
            }

            test();
            ?>


            This script will not produce any output because the echo statement refers to a local version of the $a variable, and it has not been assigned a value within this scope. You may notice that this is a little bit different from the C language in that global variables in C are automatically available to functions unless specifically overridden by a local definition. This can cause some problems in that people may inadvertently change a global variable. In PHP global variables must be declared global inside a function if they are going to be used in that function.






            share|improve this answer












            The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. This
            single scope spans included and required files as well. For example:



            <?php
            $a = 1;
            include 'b.inc';
            ?>


            Here the $a variable will be available within the included b.inc script. However, within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope. For example:



            <?php
            $a = 1; /* global scope */

            function test()
            {
            echo $a; /* reference to local scope variable */
            }

            test();
            ?>


            This script will not produce any output because the echo statement refers to a local version of the $a variable, and it has not been assigned a value within this scope. You may notice that this is a little bit different from the C language in that global variables in C are automatically available to functions unless specifically overridden by a local definition. This can cause some problems in that people may inadvertently change a global variable. In PHP global variables must be declared global inside a function if they are going to be used in that function.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Sep 20 '15 at 11:18









            Josip Ivic

            2,89983254




            2,89983254












            • It seems a little dishonest to copy verbatim the PHP manual page on variable scope without attribution.
              – bishop
              Oct 29 '18 at 20:02




















            • It seems a little dishonest to copy verbatim the PHP manual page on variable scope without attribution.
              – bishop
              Oct 29 '18 at 20:02


















            It seems a little dishonest to copy verbatim the PHP manual page on variable scope without attribution.
            – bishop
            Oct 29 '18 at 20:02






            It seems a little dishonest to copy verbatim the PHP manual page on variable scope without attribution.
            – bishop
            Oct 29 '18 at 20:02







            protected by Samuel Liew Oct 5 '15 at 9:00



            Thank you for your interest in this question.
            Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



            Would you like to answer one of these unanswered questions instead?



            Popular posts from this blog

            'app-layout' is not a known element: how to share Component with different Modules

            android studio warns about leanback feature tag usage required on manifest while using Unity exported app?

            WPF add header to Image with URL pettitions [duplicate]