note 59676 added to language.variables.scope

From: Date: Tue, 13 Dec 2005 08:22:59 +0000
Subject: note 59676 added to language.variables.scope
Groups: php.notes 
Request: Send a blank email to php-notes+get-100047@lists.php.net to get a copy of this message
Some interesting behavior (tested with PHP5), using the static-scope-keyword inside of class-methods. <?php class sample_class { public function func_having_static_var($x = NULL) { static $var = 0; if ($x === NULL) { return $var; } $var = $x; } } $a = new sample_class(); $b = new sample_class(); echo $a->func_having_static_var()."\n"; echo $b->func_having_static_var()."\n"; // this will output (as expected): // 0 // 0 $a->func_having_static_var(3); echo $a->func_having_static_var()."\n"; echo $b->func_having_static_var()."\n"; // this will output: // 3 // 3 // maybe you expected: // 3 // 0 ?> One could expect "3 0" to be outputted, as you might think that $a->func_having_static_var(3); only alters the value of the static $var of the function "in" $a - but as the name says, these are class-methods. Having an object is just a collection of properties, the functions remain at the class. So if you declare a variable as static inside a function, it's static for the whole class and all of its instances, not for each object. Maybe it's senseless to post that.. cause if you want to have the behaviour that I expected, you can simply use a variable of the object itself: <?php class sample_class { protected $var = 0; function func($x = NULL) { $this->var = $x; } } ?> I believe that all normal-thinking people would never even try to make this work with the static-keyword, for those who try (like me), this note maybe helpfull. ---- Manual Page -- http://www.php.net/manual/en/language.variables.scope.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+59676 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+59676&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+59676&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+59676&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+59676&report=yes&reason=useless Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+59676&report=yes&reason=non-english Delete: already in docs -- http://master.php.net/manage/user-notes.php?action=delete+59676&report=yes&reason=already+in+docs Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+59676&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+59676&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#100047) next »