PHP Object-oriented keyword static, self

Source: Internet
Author: User

Knowledge Points:

Static can modify the properties or methods within the class, the modified property or method outside the class, cannot be instantiated as an object access, but rather use the class itself to access, and the statically method if you want to use a static property, you need the self:: Such a way to access the static property, which represents the class itself, Rather than $this, $this mean the object itself after the instantiation, there is a big difference between the two.

The self, which is the class itself, can help a method invoke a static property by using the-(because static properties can only be accessed by the class)

Code:

<?phpclass test{static $one = ' q ';p ublic function __construct () {}static function test () {echo ' Test succeeded! ‘;} Public Function GetOne () {return self:: $one;}} echo Test:: $one;//property Access succeeded Test::test ();//method execution succeeded $ A = new Test (' s '); $res = $a->getone (); Echo $res;//property Access succeeded?>

Significance:

The project encountered a lot of static program functions (for example: Database connection), we passed in parameters than other programs always pass fixed parameters, each new class will always consume some resources, if possible, we want to instantiate the good one object in advance, each time the program needs him to directly call this object, That's OK, you need to use self+static to make some modifications to the original class so that the class automatically generates the object, and we use this object. This idea is a singleton pattern.

PHP Object-oriented keyword static, self

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.