Php static variable example

Source: Internet
Author: User
Tags php tutorial

Class test
{
Public static function (){}
Public function B (){}
}
$ Obj = new test;

Call code

Test: ();
$ Obj-> ();
$ Obj-> B ();

 

Example: an example of static variables
<? Php Tutorial

Class myobject {
Public static $ mystaticvar = 0;

Function mymethod (){
//: A limited-scope operator.
// Use the self scope instead of the $ this scope
// Because $ this indicates only the current instance of the class, and self: indicates the class itself.
Self: $ mystaticvar + = 2;
Echo self: $ mystaticvar. "<br/> ";
 }
}

$ Instance1 = new myobject ();
$ Instance1-> mymethod (); // Display 2

$ Instance2 = new myobject ();
$ Instance2-> mymethod (); // Display 4

?>

 

<? Php

Class myobject {
Public static $ myvar = 10;
}

Echo myobject: $ myvar;

// Result: 10
?>


This function is useless because $ w3sky is set to 0 and "0" is output every time you call it ". Adding $ w3sky ++ to the variable does not work because $ w3sky does not exist once you exit this function. To write a counting function that does not lose the current count value, you must define the variable $ w3sky as static:


Example of static variables

<? Php
Function test ()
   {
Static $ w3sky = 0;
Echo $ w3sky;
$ W3sky ++;
   }
?>
Now, every time you call the test () function, the value of $ w3sky is output and added with one.

View instances


<? 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"; // can be dynamically called after php 5.3.0
Print bar: $ my_static. "n ";
$ Bar = new bar ();
Print $ bar-> foostatic (). "n ";
?>
For more details, see: http://www.111cn.net/phper/php-cy/33303.htm

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.