Example of a PHP static variable

Source: Internet
Author: User

Class Test
{
public static function A () {}
Public Function B () {}
}
$obj = new test;

Calling code

Test::a ();
$obj->a ();
$obj->b ();

Examples of examples that require static variables
<?php Tutorials

Class MyObject {
public static $mystaticvar = 0;

function MyMethod () {
:: Scoping operators for scopes
Use the self scope instead of the $this scope
Because $this represents only the current instance of the class, and self:: The expression is the class itself
Self:: $mystaticvar + = 2;
echo Self:: $mystaticvar. "<br/>";
}
}

$instance 1 = new MyObject ();
$instance 1->mymethod (); Showing 2

$instance 2 = new MyObject ();
$instance 2->mymethod (); Showing 4

?>

<?php

Class MyObject {
public static $myvar = 10;
}

echo MyObject:: $myvar;

Results: 10
?>


This function is of little use because the value of $w 3sky is set to 0 and output "0" each time it is called. Adding a variable to a $w 3sky++ has no effect, because once you exit this function, the variable $w 3sky does not exist. To write a count function (www.111cn.net) that does not lose this count value, define the variable $w 3sky as static:


Examples of using static variables

<?php
function test ()
{
static $w 3sky = 0;
echo $w 3sky;
$w 3sky++;
}
?>
Now, each call to the test () function outputs the value of $w 3sky and adds one.

See an example


<?php
Class Foo
{
public static $my _static = ' foo ';
Public Function Staticvalue () {
Return self:: $my _static;
}
}
Class Bar extends Foo
{
Public Function foostatic () {
Return Parent:: $my _static;
}
}
Print foo:: $my _static. "N";
$foo = new Foo ();
Print $foo->staticvalue (). "N";
Print $foo->my_static. "N"; Undefined "Property" my_static
Print $foo:: $my _static. "N";
$classname = ' Foo ';
Print $classname:: $my _static. "N"; PHP 5.3.0 can be dynamically called after
Print bar:: $my _static. "N";
$bar = new Bar ();
Print $bar->foostatic (). "N";
?>

From:http://www.111cn.net/phper/php/php-static.htm

Example of a PHP static variable

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.