Static variables in PHP
Asked Answered
E

6

55

I have found different information regarding static variables in PHP but nothing that actually explains what it is and how it really works.

I have read that when used within a class that a static property cannot be used by any object instantiated by that class and that a static method can be used by an object instantiated by the class?

However, I have been trying to research what a static variable does within a function that is not in a class. Also, does a static variable within a function work somewhat like closure in javascript or am I totally off in this assumption?

Etheline answered 22/9, 2011 at 0:38 Comment(4)
See also stackoverflow.com/search?q=%5Bphp%5D+staticExcommunicative
The value of a static function remains a constant. For eg if $static=4; and then inside a function we write $static=$static+10; ,it becomes 14, but once that function is again called it's value will be 4 itself initially in the function. I think it is so. Thanks,Athene
@look4php a static is NOT constant. If the static property is changed it remains changed for the execution of the script.Cyclopean
ok Hamish, a small eg would be helpful,if u have timeAthene
S
75

I have read that when used within a class that a static property cannot be used by any object instantiated by that class

It depends on what you mean by that. eg:

class Foo {
    static $my_var = 'Foo';
}

$x = new Foo();

echo $x::$my_var;  // works fine
echo $x->my_var;   // doesn't work - Notice: Undefined property: Foo::$my_var

and that a static method can be used by an object instantiated by the class???

Yes, an instantiated object belonging to the class can access a static method.

The keyword static in the context of classes behave somewhat like static class variables in other languages. A member (method or variable) declared static is associated with the class and rather than an instance of that class. Thus, you can access it without an instance of the class (eg: in the example above, I could use Foo::$my_var)


However, I have been trying to research what a static variable does within a function that is not in a class.

Also, does a static variable within a function work somewhat like closure in javascript or am I totally off in this assumption.

Outside of classes (ie: in functions), a static variable is a variable that doesn't lose its value when the function exits. So in sense, yes, they work like closures in JavaScript.

But unlike JS closures, there's only one value for the variable that's maintained across different invocations of the same function. From the PHP manual's example:

function test()
{
    static $a = 0;
    echo $a;
    $a++;
}

test();  // prints 0
test();  // prints 1
test();  // prints 2

Reference: static keyword (in classes), (in functions)

Stillness answered 22/9, 2011 at 0:40 Comment(4)
I don't understand this part: But unlike JS closures, there's only one value for the variable that's maintained across different invocations of the same function. Isn't it exactly like JS closures in that sense? How does this count as a difference? eg. var a = 0; function test(){ alert(a++); } test(); test(); test(); does the same thing as your example.Stereochromy
@AsadSaeeduddin, if you do function test(){ var a=0; alert(a++); } test(); test(); test();, which is more like the code from the manual, you get 0, 0, 0, 0.Dibru
@Dibru There's no closures in the snippet you've providedStereochromy
@AsadSaeeduddin sorry. var a=0; function test() { a=0; alert(a++); } test(); test(); test(); The point being made is that the inner assign has no effect (after the first time) in PHP, unlike in JS.Dibru
U
41

static has two uses in PHP:

First, and most commonly, it can be used to define 'class' variables/functions (as opposed to instance variables/functions), that can be accessed without instantiating a class:

class A {
  public static $var = 'val'; // $var is static (in class context)
  public $other_var = 'other_val'; // non-static
}

echo A::$var; // val
echo A::$other_var // doesn't work (fatal error, undefined static variable)

$a = new A;
echo $a->var // won't work (strict standards)
echo $a->other_var // other_val

Secondly, it can be used to maintain state between function calls:

function a() {
  static $i = 0;
  $j = 0;
  return array($i++, $j++);
}
print_r(a()); // array(0, 0)
print_r(a()); // array(1, 0)
print_r(a()); // array(2, 0)
//...

Note that declaring a variable static within a function works the same regardless of whether or not the function is defined in a class, all that matters is where the variable is declared (class member or in a function).

Unrestrained answered 22/9, 2011 at 0:58 Comment(0)
N
11

A static variable in a function is initialized only in the first call of that function in its running script.

Neurology answered 7/10, 2015 at 3:45 Comment(0)
C
11

At first i will explain what will happen if static variable is not used

function somename() {
    $var = 1;
    echo $var . "<br />";
    $var++;
}
somename(); //1
somename(); //1
somename(); //1

If you run the above code the output you gets will be 1 1 1 . Since everytime you called that function variable assigns to 1 and then prints it.


Now lets see what if static variable is used

function somename() {
    static $var = 1;
    echo $var . "<br />";
    $var++;
}
somename(); //1
somename(); //2
somename(); //3

Now if you run this code snippet the output will be 1 2 3.

Note: Static keeps its value and stick around everytime the function is called. It will not lose its value when the function is called.

Cowbane answered 9/12, 2016 at 20:44 Comment(0)
M
3
class Student {
    static $total_student = 0;
    static  function add_student(){
        return Student::$total_student++;
    }
}

First: for the add_student function, the best practice is to use static not public. Second: in the add_student function, we are using Student::$total_student,not use $this->total_student. This is big different from normal variable. Third:static variable are shared throughout the inheritance tree.

take below code to see what is the result:

class One {
    static $foo ;
}
class Two extends One{}
class Three extends One{}
One::$foo = 1;
Two::$foo = 2;
Three::$foo = 3;
echo One::$foo;
echo Two::$foo;
echo Three::$foo;`
Meara answered 5/6, 2017 at 20:33 Comment(0)
K
2

A static class property can also be used to share a value between all instances of that class.

<?php

class Foo {
    public static array $static = [];
    public array $nonStatic = [];

    public function add(string $text): void
    {
        self::$static[] = $text;
        $this->nonStatic[] = $text;
    }
}

$first = new Foo();
$first->add('Lorem ipsum');

$second = new Foo();
$second->add('Dolor sit amet');

var_dump($first::$static); // ['Lorem ipsum', 'Dolor sit amet']
var_dump($first->nonStatic); // ['Lorem ipsum']
var_dump($second::$static); // ['Lorem ipsum', 'Dolor sit amet']
var_dump($second->nonStatic); // ['Dolor sit amet']

For example I've recently used that approach for a fake service dispatching messages to AMQP (a fake service which overrides the regular one when run in functional tests) in a Symfony-based project to check what was supposed to be dispatched during several HTTP requests.

Kelwunn answered 31/10, 2023 at 10:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.