If you want to reach the technical ceiling, then the learning process lies in knowing what is happening and why. Today we will discuss the underlying copy-on-write (also called split-on-write) of PHP. First, let’s take a look at a piece of code: I believe everyone knows the output results of the two pieces of code, but today we will talk about what happened. The picture below is the structure of PHP storage variables (comments have been written for convenience of explanation), zend.h is in the Zend directory. As you can see, the structure stores variable values, and several variables point to the"/> If you want to reach the technical ceiling, then the learning process lies in knowing what is happening and why. Today we will discuss the underlying copy-on-write (also called split-on-write) of PHP. First, let’s take a look at a piece of code: I believe everyone knows the output results of the two pieces of code, but today we will talk about what happened. The picture below is the structure of PHP storage variables (comments have been written for convenience of explanation), zend.h is in the Zend directory. As you can see, the structure stores variable values, and several variables point to the">
search
HomeBackend DevelopmentPHP TutorialPHP underlying analysis: About copying the plural of cow cow when writing Shengcai Forum ww7349cow Japanese cow milk stone

If you want to reach the ceiling of technology, then the learning process lies in knowing what is happening and why.

Today we will discuss the underlying copy-on-write (also called split-on-write) of PHP.

First, let’s take a look at a piece of code:
PHP underlying analysis: About copying the plural of cow cow when writing Shengcai Forum ww7349cow Japanese cow milk stone

I believe everyone knows the output results of the two pieces of code, but today we will talk about what happened.

The picture below is the structure of PHP storage variables (comments have been written for convenience of explanation), zend.h is in the Zend directory.

You can see that the structure stores information about the variable value, how many variables point to the structure, variable type, whether it is a reference variable, etc.
PHP underlying analysis: About copying the plural of cow cow when writing Shengcai Forum ww7349cow Japanese cow milk stone

So what happens with the first print? The variable information enters a structure, and the correlation is as follows:
PHP underlying analysis: About copying the plural of cow cow when writing Shengcai Forum ww7349cow Japanese cow milk stone

$name = '8:30 in the evening';
$myName = $name;

At this time, $name and $myName share a structure, and refcount__gc is 2.

We found that $myName = $name; did not actively turn into two structures during this process (this is also considered a kind of optimization within PHP, using only one structure, saving memory).

So when the code runs to $myName = ‘gzchen’;, how does the structure change? Since the structure is shared by two variables in the first output, will changing one of the variables at this time cause the two values ​​to change together? Purely from the logic of the structure, it is possible. After all, everyone shares this structure.

Then let’s take a look at what the second printing will look like. The relevant changes are as follows:
PHP underlying analysis: About copying the plural of cow cow when writing Shengcai Forum ww7349cow Japanese cow milk stone

did not change $name and $myName to 'gzchen' at the same time as we thought, but copied one more The two structures come out, and the two structures correspond to $name and $myName respectively.

This is Copy-on-write (COW) causing trouble. It does not split into two structures when $myName = $name; is assigned, but takes effect when we rewrite one of the variables. , belongs to a kind of slow replication (also called slow division).

The pseudo code is as follows:
PHP underlying analysis: About copying the plural of cow cow when writing Shengcai Forum ww7349cow Japanese cow milk stone

Let’s look at another piece of code:
PHP underlying analysis: About copying the plural of cow cow when writing Shengcai Forum ww7349cow Japanese cow milk stone

The output is ‘b’, what happened in the middle?

In fact, during the foreach traversal process, $arr (the original array) is not directly manipulated, but $arr is copied into an $arrcopy (actually a copy, I use $arrcopy instead here). Foreach is in the traversal process In fact, the operation is always $arrcopy. The general process is as follows:

PHP underlying analysis: About copying the plural of cow cow when writing Shengcai Forum ww7349cow Japanese cow milk stone

is actually the same as the example given above. We can see that at the beginning ($arr = $arrcopy) still share the same structure. , but $arr[$k] = $v is assigned again, copy-on-write occurs, and the structure is split.

And as mentioned before, foreach operates on $arrcopy, so the structure pointer of $arr is stuck at the first position (because the structure is different, $arrcopy cannot assign a value to $arr synchronously).

In fact, this kind of technology is usually only used in interviews. After all, there are only a few people who use this writing method in daily development. Friends who don’t understand it for the time being don’t need to pay too much attention. As long as you know that there is a situation of “copy while writing”. That's it.

The above introduces the underlying analysis of PHP: Regarding copying cow when writing, including cow and php content, I hope it will be helpful to friends who are interested in PHP tutorials.

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
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MantisBT

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.