Home  >  Article  >  Backend Development  >  PHP object-oriented development - singleton mode

PHP object-oriented development - singleton mode

黄舟
黄舟Original
2016-12-29 11:07:441627browse

HP's global variables bring great flexibility to programming, but the unconstrained nature of global variables also brings great hidden dangers. The singleton pattern can be a good alternative to global variables.

Suppose there is a flower. Everyone who sees it will water the flower and then appreciate it.

class flower{

	function __construct(){
		echo date('Y-m-d H:i:s').'浇了花';
	}
	
	public function look(){
		return '一朵美丽的花';
	}

}

$a=new flower();//将输出:2013-01-08 09:37:54浇了花
echo $a->look();//将输出:一朵美丽的花
$b=new flower();//将输出:2013-01-08 09:37:54浇了花
echo $b->look();//将输出:一朵美丽的

It can be seen that if there are more and more people, the flowers will be drowned sooner or later. What we need is that as long as the first person to see the flowers water the flowers, other people do not need to water the flowers.

class flower{  
      
    private static $instance;  
  
    private function __construct(){  
        echo date('Y-m-d H:i:s').'浇了花';  
    }  
      
    public static function getInstance(){  
        if(empty(self::$instance)){  
            self::$instance=new self();  
        }  
        return self::$instance;  
    }  
      
    public function look(){  
        return '一朵美丽的花';  
    }  
  
}  
  
$a=flower::getInstance();//将输出:2013-01-08 09:52:43浇了花  
echo $a->look();//将输出:一朵美丽的花  
  
$b=flower::getInstance();//不会输出  
echo $b->look();//将输出:一朵美丽的

The singleton mode is suitable for environments that only need to obtain the same instance, such as mysql database connections and other operations.

The above is the content of PHP object-oriented development - singleton mode. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn