OOP, static variables in methods.

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
bokehman
Forum Regular
Posts: 509
Joined: Wed May 11, 2005 2:33 am
Location: Alicante (Spain)

OOP, static variables in methods.

Post by bokehman »

Code: Select all

<?php

class myClass
{
	function myMethod($in = null)
	{
		static $i = 0;
		!$in or $i++;
		echo $i;
	}
}

$class = new myClass();
$class->myMethod();
$class->myMethod(1);

$class2 = new myClass();
$class2->myMethod();
$class2->myMethod(1);

$class3 = new myClass();
$class3->myMethod();
$class3->myMethod(1);

?>
That prints:

Code: Select all

011223
Is that the expected bahaviour or a bug? I thought each new object was unique and nothing going on in another object should affect it but this shows that is not the case.

Any thoughts on this?
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post by Ollie Saunders »

The phenomenon is called "early binding of local statics" or something like that.

its not a bug, its PHP; it's not a particularly great feature, many would prefer late binding instead; it may be changed to late binding for PHP 6.
User avatar
bokehman
Forum Regular
Posts: 509
Joined: Wed May 11, 2005 2:33 am
Location: Alicante (Spain)

Post by bokehman »

ole wrote:it may be changed to late binding for PHP 6.
Well that would be even worse because the script would become version dependant.
User avatar
bokehman
Forum Regular
Posts: 509
Joined: Wed May 11, 2005 2:33 am
Location: Alicante (Spain)

Post by bokehman »

Now you have given me that bit of info I have found "Early binding" and "Static variables" are synonomous as are "Late binding" and "Dynamic variables" the difference being "Static variables" are read in at compile time rather than run time.
Post Reply