Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static within non-static method is shared between instances

Tags:

php

I've come across some unexpected behavior with static variables defined inside object methods being shared across instances. This is probably known behavior, but as I browse the PHP documentation I can't find instances of statically-defined variables within object methods.

Here is a reduction of the behavior I've come across:

<?php

class Foo {
  public function dofoo() {
    static $i = 0;
    echo $i++ . '<br>';
  }
}

$f = new Foo;
$g = new Foo;

$f->dofoo(); // expected 0, got 0
$f->dofoo(); // expected 1, got 1
$f->dofoo(); // expected 2, got 2

$g->dofoo(); // expected 0, got 3
$g->dofoo(); // expected 1, got 4
$g->dofoo(); // expected 2, got 5

Now, I would have expected $i to be static per instance, but in reality $i is shared between the instances. For my own edification, could someone elaborate on why this is the case, and where it's documented on php.net?

like image 283
Annika Backstrom Avatar asked Feb 23 '10 20:02

Annika Backstrom


People also ask

Are static methods shared?

There will always be only one copy of static field belonging to it. The value of this static field will be shared across all objects of either the same or any different class.

Can you call a static method from a non static instance method?

A static method can call only other static methods; it cannot call a non-static method.

Can we access static variable in non static method?

non-static methods can access any static method and static variable also, without using the object of the class. In the static method, the method can only access only static data members and static methods of another class or same class but cannot access non-static methods and variables.

Can a class have both static and non static methods?

Static class always contains static members. Non-static class may contain both static and non-static methods. Static class does not contain an instance constructor. Non-static class contains an instance constructor.


1 Answers

This is the very definition of static.

If you want members to be specific to an instance of an object, then you use class properties

e.g.

<?php

class Foo
{
    protected $_count = 0;
    public function doFoo()
    {
        echo $this->_count++, '<br>';
    }
}

Edit: Ok, I linked the documentation to the OOP static properties. The concept is the same though. If you read the variable scope docs you'll see:

Note: Static declarations are resolved in compile-time.

Thus when your script is compiled (before it executes) the static is "setup" (not sure what term to use). No matter how many objects you instantiate, when that function is "built" the static variable references the same copy as everyone else.

like image 55
hobodave Avatar answered Nov 14 '22 22:11

hobodave