From: Mark W. <ma...@rw...> - 2011-04-21 09:57:19
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1"> </head> <body bgcolor="#ffffff" text="#000000"> I have just discovered a new OOP technique that I had never heard about before.<br> Well i've been writing embedded C recently and found that you could have static variables within a function.<br> Thus that particular variable maintains state in each subsequent call of the same function whilst keeping local scope instead of class level scope / global scope.<br> <br> Now it turns out this is also possible in PHP so I thought I would share it with everyone in case they find a good use for it. An example is shown below:<br> <br> <div class="example-contents"> <div class="phpcode"><code><span style="color: rgb(0, 0, 0);"> <span style="color: rgb(0, 0, 187);"><?php<br> </span><span style="color: rgb(0, 119, 0);">function </span><span style="color: rgb(0, 0, 187);">test</span><span style="color: rgb(0, 119, 0);">()<br> {<br> static </span><span style="color: rgb(0, 0, 187);">$a </span><span style="color: rgb(0, 119, 0);">= </span><span style="color: rgb(0, 0, 187);">0</span><span style="color: rgb(0, 119, 0);">;<br> echo </span><span style="color: rgb(0, 0, 187);">$a</span><span style="color: rgb(0, 119, 0);">;<br> </span><span style="color: rgb(0, 0, 187);">$a</span><span style="color: rgb(0, 119, 0);">++;<br> }<br> </span><span style="color: rgb(0, 0, 187);">test();<br> test();<br> test();<br> ?><br> <br> Information found here: <a class="moz-txt-link-freetext" href="http://php.net/manual/en/language.variables.scope.php">http://php.net/manual/en/language.variables.scope.php</a><br> <br> Cheers!<br> Mark</span></span></code><br> </div> </div> <pre class="moz-signature" cols="72">-- _____________________________________________ Mob: 07725 695178 Email: <a class="moz-txt-link-abbreviated" href="mailto:ma...@rw...">ma...@rw...</a></pre> </body> </html> |