Static methods in PHP class

Source: Internet
Author: User
Generally, in WEB applications, it is difficult for us to use some advanced (or unique) usage of classes to learn how to use static methods. Static method definition

It is easy to define the static method. before declaring the keyword function, add static, for example:

class A {  static function fun()  {  // do somathing  } } 
Static method usage

It is similar to a static variable and does not need to be instantiated. it can be called directly using:. for example:

A::fun()
Comparison of common methods

Because the call to a static method does not need to be instantiated, an error occurs when you reference the attributes or methods of the class in the static method, that is, self and $ this are incorrect.

class MyClass{    public $num = 5;    function __construct()    {        $this->num = 10;    }    function fun_1()    {        echo "I am a public method named fun_1.\n";        echo "The num of object is {$this->num}.\n";    }    static function fun_2()    {        echo "I am a static method named fun_2.\n";    }    function fun_3($n)    {        echo "The arg is {$n}\n";    }}$m = new MyClass;$m->fun_1();$m->fun_2();$m->fun_3('test');MyClass::fun_1();MyClass::fun_2();MyClass::fun_3('test');

Output result:

lch@localhost:php $ php class_method.phpI am a public method named fun_1.The num of object is 10.I am a static method named fun_2.The arg is testI am a public method named fun_1.PHP Fatal error:  Using $this when not in object context in /Users/lch/program/php/class_method.php on line 14

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.