Pastoid

The page you are looking at now is at this URL: http://pastoid.com/atx

This paste was last updated on March 24, 2009 at 12:54 am.

Pasted Coderaw

 Wait, What? Yeah that's what I thought too. Still no Idea what I'm talking about? Well, let's take a look at the following code. Let's call it "fred".
 
<pre><code class="highlight php">
class foo {
	function bar( $b = 0 )
	{
		static $a = 0;
		if ( $b ) {
			$a = $b;
		}	
		 echo $a;
	}
}
 
$faz = new foo;
$faz->bar(3);
$baz = new foo;
$baz->bar();
foo::bar();
foo:bar(1); 
$faz->bar();
</code></pre>
 
The code above, named "fred", basically creates a static variable <code class="highlight php">$a</code> inside the function <code class="highlight php">foo()</code>. When you call <code class="highlight php">foo(0)</code> it outputs the value of <code class="highlight php">$a</code>. When you call <code class="highlight php">foo('x')</code> , where x can be anything, it updates the value of <code class="highlight php">$a</code> with <code class="highlight php">'x'</code>, and outputs the new result.
 
Now, what would expect "fred" to output? If your like me, then you are completely wrong. "fred" will actually output the following code.
 
<pre><code class="highlight php">
<![CDATA[
/*
Actual Outputs:
$faz->bar(3); ==> 3
$baz->bar();  ==> 3
foo::bar();      ==> 3
foo:bar(1);     ==> 1
$faz->bar();   ==> 1
 
Expected outputs:
$faz->bar(3); ==> 3
$baz->bar();  ==> 0
foo::bar();      ==> 0
foo:bar(1);     ==> 1
$faz->bar();   ==> 3
*/
]]>
</code></pre>
 
Yes, that's what I said at the start, "Persistent Static Variables Across Instances". The static variable <code class="highlight php">$a</code> actually persists across the two instances of foo that "fred" created, and even into the static method call. This was completely unexpected, at least by me. So I'll ask, does anyone know if this is actually the expected behaviour, and why it is or is not?
 
 

Toggle wordwrap

Referring DomainHits
Unknown Referer 127
pastoid.com 6
search.live.com 1
Is this paste spam?
<Hide