note 120750 added to language.variables.scope
| From: | dexen dot devries at gmail dot com | Date: | Mon, 06 Mar 2017 15:54:48 +0000 |
| Subject: | note 120750 added to language.variables.scope | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-208871@lists.php.net to get a copy of this message | ||
If you have a static variable in a method of a class, all DIRECT instances of that class share that
one static variable.
However if you create a derived class, all DIRECT instances of that derived class will share one,
but DISTINCT, copy of that static variable in method.
To put it the other way around, a static variable in a method is bound to a class (not to instance).
Each subclass has own copy of that variable, to be shared among its instances.
To put it yet another way around, when you create a derived class, it 'seems to' create a
copy of methods from the base class, and thusly create copy of the static variables in those
methods.
Tested with PHP 7.0.16.
<?php
require 'libs.php';
require 'setup.php';
class Base {
function test($delta = 0) {
static $v = 0;
$v += $delta;
return $v;
}
}
class Derived extends Base {}
$base1 = new Base();
$base2 = new Base();
$derived1 = new Derived();
$derived2 = new Derived();
$base1->test(3);
$base2->test(4);
$derived1->test(5);
$derived2->test(6);
var_dump([ $base1->test(), $base2->test(), $derived1->test(), $derived2->test() ]);
# => array(4) { [0]=> int(7) [1]=> int(7) [2]=> int(11) [3]=> int(11) }
# $base1 and $base2 share one copy of static variable $v
# derived1 and $derived2 share another copy of static variable $v
----
Server IP: 72.52.91.14
Probable Submitter: 89.229.69.253
----
Manual Page -- http://php.net/manual/en/language.variables.scope.php
Edit -- https://master.php.net/note/edit/120750
Del: integrated -- https://master.php.net/note/delete/120750/integrated
Del: useless -- https://master.php.net/note/delete/120750/useless
Del: bad code -- https://master.php.net/note/delete/120750/bad+code
Del: spam -- https://master.php.net/note/delete/120750/spam
Del: non-english -- https://master.php.net/note/delete/120750/non-english
Del: in docs -- https://master.php.net/note/delete/120750/in+docs
Del: other reasons-- https://master.php.net/note/delete/120750
Reject -- https://master.php.net/note/reject/120750
Search -- https://master.php.net/manage/user-notes.php