Example of a single example class in PHP

Source: Internet
Author: User
Tags php example

This article mainly introduces a single example class in PHP example, this article directly gives code examples, the need for friends can refer to the

The single instance class in PHP is very meaningful for data exchange, saving memory. Write a simple example.

Class 1, single instance class itself:

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14-15 16 Class UTIL {private static $instance; public function get () {if (!self:: $instance) {self:: $instance = new UTIL ();} ret Urn self:: $instance; Public $number = 10; Public function Change ($num) {$this->number + = $num;} public Function Getnum () {return $this->number;}}

Class 2, use the application class of the preceding single instance class:

?

1 2 3 4 5 6 7 8 9 10 11-12 Class Singlea {private $numInst; function __construct () {$this->numinst = Util::get ();} Public Function Change ($num) {$this->numinst->change ($num);} public Function Getnum () {return $this->numinst->getnum ();}}

Class 3, homogeneous 2:

?

1 2 3 4 5 6 7 8 9 10 11-12 Class Singleb {private $numInst; function __construct () {$this->numinst = Util::get ();} Public Function Change ($num) {$this->numinst->change ($num);} public Function Getnum () {return $this->numinst->getnum ();}}

Last is the place to call:

?

1 2 3 4 5 6 7 8 $instA = new Singlea (); $instA->change (100); Var_dump (' Singlea CHANGED: '); Var_dump ($instA->getnum ()); $instB = new Singleb (); $instB->change (-510); Var_dump (' Singleb CHANGED: '); Var_dump ($instB->getnum ());

The final display result:

?

1 2 3 4 String ' Singlea CHANGED: ' (length=17) int110 string ' Singleb CHANGED: ' (length=17) int-400
Related Article

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.