The last article introduced you to "How to use PHP to make an MVC framework in general process". This article continues to introduce to you what is a design pattern in PHP? What is a singleton? how to use? It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
PHP Advanced Practice-Design Pattern
Overview of Design Pattern
Design pattern (Designpattern) is a -A summary of code design experience that has been used repeatedly, is known to most people, and has been cataloged. The purpose of using design patterns is to reuse code, make the code easier to understand by others, and ensure code reliability. There is no doubt that design patterns are win-win for ourselves, others, and the system. Design patterns make code compilation truly engineering. Design patterns are the cornerstone of software engineering, just like the bricks and stones of a building.
Classic definition of pattern:Each pattern describes a problem that constantly arises in our environment, and then describes
the solution to the problem In this way, we can reuse existing solutions countless times without repeating the same work. That is, a pattern is a solution to a problem in a specific environment
There are two schools now. Some people recommend using design patterns, and some people do not recommend using design patterns!
High cohesion , Low coupling
The degree of aggregation in the class must be very high
The relationship between classes must be minimized
Let’s take the code as an example, first create A new file, then we first write a class, and then we create two objects. Whether the two objects we create now are the same space and the same object, we need to judge through the if statement. The code is as follows:
<?php class Dog { } $dog1 = new Dog(); $dog2 = new Dog(); if ($dog1=== $dog2) { echo '这是同一个对象'; } else { echo '这是两个不同的对象'; }
The results are as follows:
We see that the results show that they are two different objects, so we need to make a singleton;
The code is as follows:This class can only create one object. The application of PHP is mainly in database applications. There will be a large number of database operations in each application. Using the singleton mode, can avoid a large number of resources consumed by new operations 1. The constructor needs to be marked as private 2. Save the static member variables of the class instance 3. Get the instance Public static methods Recommended learning: " The above is the detailed content of What are design patterns in PHP? What is a singleton? how to use?. For more information, please follow other related articles on the PHP Chinese website!private function_construct( ) { }
//静态属性保存单例对象
static private $instance;
//通过静态方法来创建单例对象
static public function getInstance()
{
/ /判断$instance是否为空,如果为空,则new- 一个对象
如果不会空,则直接返回
if( !self: :$instance) {
self: :$instance = new self();
}
return self: : $instance ;
}