每日一记之php原型模式
原型模式是指通过现有的实例通过拷贝得到新的实例。
在程序的设计中,有的时候我们去实例化某个对象需要做太多的初始化工作,非常耗时的时候,我们可以考虑采用原型模式来得到新的实例。
其实在php中我们很容易通过clone关键字去实现对象的复制。另外通过魔术方法__clone()指定在clone的时候需要进行的操作。这个其实就是原型模式的实现方式了。当然,有时候为了让代码看起来比较优雅,比较完善。我们可以自己去写相关的实现方式,当然也需要用到clone关键字。
<?phpinterface Cloneable{ public function copy();}class Task implements Cloneable{ public $name; public $startTime; public function __construct($name){ //这里实例化Task需要做很多工作 $this->name = $name; $this->startTime = time(); } public function copy(){ return clone $this; }}
在这里我们可以创建一个task
$task1 = new Task("Task1");
现在我们已经有了一个Task的实例了,我们要得到一个新的task实例就可以通过clone的方法
$task2 = $task1->copy();
可是现在这样我们打印$task1和$task2的startTime,两者是一样的,而我们又希望clone出来的对象时间应该是当前时间,怎么做呢?所以我们就得去写__clone方法,该方法在一个对象尝试进行clone的时候会自动调用。改良后的代码如下
class Task implements Cloneable{ public $name; public $startTime; public function __construct($name){ //这里实例化Task需要做很多工作 $this->name = $name; $this->startTime = time(); } public function __clone(){ //在克隆的时候把startTime设为当前时间 $this->startTime = time(); //克隆的时候需要执行的操作 } public function copy(){ return clone $this; }}
这样克隆出来的对象的startTime就更正为当前时间了。
当然了,这只是一个简单的原型模式,在实际的克隆中,又分为浅克隆和深克隆。
浅克隆: 即对象在调用clone方法时只克隆基本的数据类型,而如果对象中包含其他对象的引用时,则copy其他对象的引用
深克隆:即除了克隆基本的数据类型外,引用的类型的数据也一并克隆。
举个例子,现在我的task类里面有一个其他对象的引用,比如Parent。相关代码如下:
class TaskParent{ public $name; public function __construct($name){ $this->name = $name; }}class Task implements Cloneable{ public $name; public $startTime; public $parent; public function __construct($name){ //这里实例化Task需要做很多工作 $this->name = $name; $this->startTime = time(); //这里直接new一个parent $this->parent = new TaskParent("do some work"); } public function __clone(){ //在克隆的时候把startTime设为当前时间 $this->startTime = time(); //克隆的时候需要执行的操作 } public function copy(){ return clone $this; }}
在上面的代码里,我们新定义了一个TaskParent的类,然后Task持有该对象的一个引用,客户端代码:
$task1 = new Task("Task1");echo $task1->parent->name."\r\n";//clone一个对象$task2 = $task1->copy();echo $task2->parent->name."\r\n";//将task1的parent的name设为另外的值$task1->parent->name = "do another work";//打印task2的parent的值echo $task2->parent->name;上面的代码最后一句话将打印 do another work,也就是说我们更改task1的parent影响到了task2。这就是典型的浅克隆,如果想实现深克隆,则可以进行如下改装
class Task implements Cloneable{ public $name; public $startTime; public $parent; public function __construct($name){ //这里实例化Task需要做很多工作 $this->name = $name; $this->startTime = time(); //这里直接new一个parent $this->parent = new TaskParent("do some work"); } public function __clone(){ //在克隆的时候把startTime设为当前时间 $this->startTime = time(); //克隆parent $this->parent = clone $this->parent; //克隆的时候需要执行的操作 } public function copy(){ return clone $this; }}
我们在__clone方法里面对parent也进行了一次克隆,所以现在打印刚才的代码就没有问题了。这就是深克隆。
在真实的编码环境中,可能一个对象持有很多其他的对象的引用,而其他对象对象又持有很多的引用。由于引用的不确定性,我们一开始的时候就应该注意,到底哪些对象需要深克隆,那些对象不需要。
如果想实现快速的深克隆,网上一哥们提供了一个简单的方法代码如下:
class Task implements Cloneable{ public $name; public $startTime; public $parent; public function __construct($name){ //这里实例化Task需要做很多工作 $this->name = $name; $this->startTime = time(); //这里直接new一个parent $this->parent = new TaskParent("do some work"); } public function __clone(){ //在克隆的时候把startTime设为当前时间 $this->startTime = time(); //克隆parent $this->parent = clone $this->parent; //克隆的时候需要执行的操作 } public function copy(){ //return clone $this; //这里不使用clone关键字,而是使用序列化和反序列化来进行 return unserialize(serialize($this)); }}
上述代码中通过serialize和unserialize来得到新的实例,经测试,完全是深克隆。关于serialize和unserialize的效率以及具体讲解将在以后补充上

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

Key players in HTTP cache headers include Cache-Control, ETag, and Last-Modified. 1.Cache-Control is used to control caching policies. Example: Cache-Control:max-age=3600,public. 2. ETag verifies resource changes through unique identifiers, example: ETag: "686897696a7c876b7e". 3.Last-Modified indicates the resource's last modification time, example: Last-Modified:Wed,21Oct201507:28:00GMT.

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

Dreamweaver CS6
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft