6

I want to know why I can't define a variable as global in class. something like this:

class MyClass {
  global $var1 = 'anything'; // syntax error
  static $var2 = 'anything'; // but it is ok
}

I know I should use static if I want use that without creating instance of a class. right ? There is just that and no any thing else ? Is global the same work?

In fact I can't understand the concept of global in php and also I can't compare it with static. I know both of them keep the values but I think the different is between lifetime (storage duration) or maybe scope. So when should I use global and when should I use static ?

  • A global variable has nothing to do with the class. It would live in the global name space. As a result you would address it "just" by its name, it would be available everywhere, thus the naming "global". In contrary to that a static member is only available inside the context of the class, you have to address it by using the class qualifier. That makes things much more precise, less error prone, which is the general reason why "globals" are frowned upon and should not be used. – arkascha Jun 28 '15 at 09:00
  • Well, if you ask me, I look at the spec:http://php.net/manual/en/language.variables.scope.php - And I don't see any mention to define global variables inside classes so why do it? – odedta Jun 28 '15 at 09:00
  • 1
    You always mix some stuff up. I would highly recommend you to read this: http://stackoverflow.com/q/16959576/3933332 – Rizier123 Jun 28 '15 at 09:22

2 Answers2

2

static and global are both used for different purpose.

  • if you want your value to be unchanged all around your project or code then you need static.

  • But if you want some variables from outside of a function and use them directly without passing them as a parameter then you need global. which fetches the value of the variable available globally and its value can be changed or modified.

    $suv = "uvre";
    
    function global_access_tes()
    {
        //want to use suv inside this function 
       global $suv;
       $suv = "changed";
    }
    global_access_tes();
    
    echo $suv;
    // output - changed
    
Meenesh Jain
  • 2,532
  • 2
  • 19
  • 29
  • But I think `static` is not unchanged. look this: `function foo() {static $i=1; echo $i; $i++; } foo(); foo(); foo();`, the output will be: `123` –  Jun 28 '15 at 09:54
  • 2
    @stack the declaration `static` has a different usage inside a class and inside a function. In a function, it would retain its value between function calls. In a class, all values are retained for the duration of the object. In the function you give above, `$i` is incremented because `static` causes it to be defined only once. – Markus AO Jun 28 '15 at 10:41
  • @MarkusAO your comment is almost the best answer for me, thanks. just when we use `static` in class ? matter exists regardless of existence of any instance of a class ? just that ?! –  Jun 28 '15 at 10:47
  • @stack, please see the answer I wrote below. I elaborated it with a bit more detail on `static`. – Markus AO Jun 28 '15 at 10:53
1

What do you need a global declaration for in a class property? We're not dealing with plain functions here. $this->var1 will get you $var1 from any method inside the class, or from an instantiated object outside the class, where the variable is public. But let's be thorough...

Illustrating "Global"

Global has no meaning for class properties; although you can use it with variables inside class methods, just as you can do with regular functions. (But there are more elegant ways to get there; it's better to avoid a load of potentially hazardous clutter in the global scope.) Let's first define a variable:

$globby = 123; // Globby is a friend living outside a function.

A function that doesn't use a global declaration can neither access a variable from outside of its scope, nor change that variable's value. The story goes like this:

function foo() {
    echo $globby; // Here we have no clue who globby is?
    $globby = 321; // Here we define globby, but then he's totally forgotten. :(
}
foo(); // => 'Notice: Undefined variable: globby'

echo $globby; // => '123' ... still the same old globby.

However, a function that declares a variable as global can both access it and modify it outside the function's scope. Also, a variable newly defined as global inside the function is accessible outside it.

function foot() {
    global $globby; // Hey globby, won't you come on in! *Globby UFO Lands*
    echo $globby; // - Who are you? - I'm globby that says 123.
    $globby = 321; // - But I'm gonna tell you to say 321 everywhere.
}

foot(); // => '123' ... this here is the good old globby from the start.
echo $globby; // => '321' ... see, globby can change outside the function scope!

Illustrating "Static" in Classes

Be aware that static for a class property doesn't work like static for a function variable. Manual: "A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope." And again: "Declaring class properties or methods as static makes them accessible without needing an instantiation of the class." (OOP Static Keyword; and Using Static Variables) Class properties retain their value for the lifetime of the object in any case.

Now, to illustrate the usage (and non-usage) of static and non-static methods (aka. "class functions") and properties (aka. "class variables"). Let's make a little class:

class foo {

    static $one = 1; // This is a static variable aka. class property.
    var $two = 2; // But this is non-static.

    static function say_one() { // This is a static method.
        echo self::$one; // Uses self:: to statically access the property.
    }

    function say_two() { // This is a non-static method.
        echo $this->two; // Uses $this-> to dynamically access the property.
    }

}

Then let's see what works and what doesn't. Non-working options are commented out.

/* Static Variables and Methods */

echo foo::$one; // => '1'
echo foo::say_one(); // => '1'

// echo foo::$two; 
// => "Fatal error: Access to undeclared static property: foo::$two"

// echo foo::say_two(); 
// => "Strict: Non-static method foo::say_two() should not be called statically. 
// & Fatal error: Using $this when not in object context."


/* Non-Static Variables and Methods */

$f = new foo(); // This here is a real effin' instantiated dynamite object. *BOOM*

echo $f->two; // => '2' 
echo $f->say_two(); // => '2'

// echo $f->one; 
// => "Strict: Accessing static property foo::$one as non static. 
// & Notice: Undefined property: foo::$one."

echo $f->say_one(); // => '1'

Hope that clarifies. Note that you can access a static method via an instantiated object, and use that to access a static variable; but you can't directly access static variables as non-static without warnings.

Let me add a note on good practice. If you find that you need to be repeatedly declaring global variables inside your functions, or passing configuration parameters etc. as function arguments, it's a sign that you should probably be factoring your code into a class instead, accessing these globals as its properties. OOP is so much cleaner to work with. You'll code happier. $OOP->nirvana();.

Markus AO
  • 4,771
  • 2
  • 18
  • 29
  • Thanks for your answer, your explanation is almost comprehensive, just please add more example of `global` application. and tell me is there any difference between `global` in class and function and anything? –  Jun 28 '15 at 10:59
  • @stack: Okay, so now it's a merry little fairytale about all things related. Let me know if something important is missing. – Markus AO Jun 28 '15 at 11:25
  • Can you tell me what happen when I create a `object` of myclass? the only usage of `static` is giving us availability variable without define a `object` of its `class`. Now I want to know when I create a instance of mytable, the proccess is very much ? or the ram will get full ? or what ? –  Jun 28 '15 at 12:07
  • The performance difference is minimal between using a static class and an object, or an "instantiated class". In some cases, a static class may in fact end up being more expensive. Your CPU and RAM usage mainly depend on what you do with the class, not how you access it. Here's a good read on static vs. instantiated class: http://stackoverflow.com/questions/1185605/when-to-use-static-vs-instantiated-classes – Markus AO Jun 28 '15 at 12:12