PHP Implementation Singleton mode

Source: Internet
Author: User

Today it looks like the singleton pattern inside the design pattern, the so-called Singleton pattern is that no matter how much this class is instantiated, the entire application only produces an object instance, and all of the objects are simply references to this object instance. Here is the code for PHP to implement a singleton pattern.

<?php

Class Person

{

Private $name;

Private $sex;

Public Function SetName ($name)

{

$this->name= $name;

}

Public Function Setage ($age)

{

$this->age= $age;

}

Public Function Printinfo ()

{

echo $this->name, $this->age;

}

}


Class single

{

private static $_instance = NULL;

Private $person = new person;

public static function getinstance ()

{

if (! $this->_instance instanceof $person) {

Self::$_instance= $person

}

return self::$_instance;

}

}


$p 1 = single::getinstance ();

$p 1->setname ("Chenlei");

$p 1->setage (28);

$p 2 = single::getinstance ();

$p 2->printinfo ();//output should be chenlei28


End.

Get off work, write more hasty, there are mistakes to point out, thank you!

PHP Implementation Singleton mode

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.