Php design mode-singleton Mode

Source: Internet
Author: User

Boat. php
Copy codeThe Code is as follows:
<? Php
Class boat {
Private static $ instance = null;
Private $ skipper;
Private $ personNum = 0;
Private $ passengers = array ();
Private function _ construct (){
}
Public static function getInstance (){
If (self: $ instance = null ){
Self: $ instance = new boat ();
}
Return self: $ instance;
}
/**
* Set the captain
*
* @ Param unknown_type $ name
*/
Public function setSkipper ($ name ){
$ This-> skipper = $ name;
}
/**
* Loader
*
* @ Param unknown_type $ person
*/
Public function load ($ person ){
If (! Emptyempty ($ person) and $ this-> personNum <= 5 ){
Array_push ($ this-> passengers, $ person );
$ This-> personNum = $ this-> personNum + 1;
}
If ($ this-> personNum> 5 ){
Echo 'this boat only load 5 person! ';
}
}
/**
* Who is mounted on the ship?
*
* @ Return unknown
*/
Public function whoInBoat (){
Return $ this-> passengers;
}
}
?>

Now let's take a look at how to attract customers.
Copy codeThe Code is as follows:
<? Php
Include 'boat. php ';
Echo "there was a river before, and there was only one boat in the river. <br> ";
$ Boat1 = boat: getInstance (); // only one instance is available because there is only one ship.
Echo "John is going to Hedong now ,";
$ Boat1-> load ('zhang san ');
Echo "<br> sitting on the ship now: <br> ";
Foreach ($ boat1-> whoInboat () as $ who ){
Echo $ who. '<br> ';
}
Echo "<br> Li Si also wants to cross the river and go east now <br> ";
$ Boat1-> load ('Li si ');
Echo "sitting on the ship now: <br> ";
Foreach ($ boat1-> whoInboat () as $ who ){
Echo $ who .',';
}
Echo "<br> Wang Wu thought there was another ship in the river. <br> ";
$ Boat2 = boat: getInstance ();
Echo "He is boarding the ship now <br> ";
$ Boat2-> load ('wang wu ');
Echo "sitting on the ship now: <br> ";
Foreach ($ boat1-> whoInboat () as $ who ){
Echo $ who .',';
}
?>

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.