Table of Contents
Reply content:
Home Backend Development PHP Tutorial I don't quite understand the operating mechanism of PHP. Please give me a solution.

I don't quite understand the operating mechanism of PHP. Please give me a solution.

Aug 04, 2016 am 09:20 AM
php

Like java and nodejs, it should be a program that continuously runs on the server. This program will always run, occupy the CPU and memory, and will process the network request when it receives it.

PHP does not seem to be a program, it is more similar to HTML. It will only be executed when it is opened. When no one accesses the PHP service, PHP will not occupy even a little bit of memory or a little bit of CPU. Is that true?


If this is the case, isn’t it difficult for PHP to encapsulate database classes? Because each user comes in and has to open a process for him, and the processes are not connected to each other. User A comes in and opens a database connection for him, and user B comes in and opens a separate database connection for him. So isn't PHP constantly connecting and disconnecting from the database? After there are more users, the overhead should be very high, right?


Is this also the reason why PHP does not have js-like setInterval or setTimeout functions?

Reply content:

Like java and nodejs, it should be a program that continuously runs on the server. This program will always run, occupy the CPU and memory, and will process the network request when it receives it.

PHP does not seem to be a program, it is more similar to HTML. It will only be executed when it is opened. When no one accesses the PHP service, PHP will not occupy even a little bit of memory or a little bit of CPU. Is that true?


If this is the case, isn’t it difficult for PHP to encapsulate database classes? Because each user comes in and has to open a process for him, and the processes are not connected to each other. User A comes in and opens a database connection for him, and user B comes in and opens a separate database connection for him. So isn't PHP constantly connecting and disconnecting from the database? After there are more users, the overhead should be very high, right?


Is this also the reason why PHP does not have js-like setInterval or setTimeout functions?

Take PHP-FPM as an example (similar to Apache MOD_PHP) to talk about the operating mechanism of PHP.
First of all, PHP-FPM is a multi-process FastCGI service implemented in C.
Each PHP-FPM worker process has a built-in PHP interpreter. It does not rely on PHP-CGI and supports resident background, such as configuration:

<code>nginx.conf: 访问io.php的请求都交给监听9001的PHP-FPM进程池处理
location = /io.php {
    include fastcgi_params;
    fastcgi_pass 127.0.0.1:9001;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}

php-fpm: 正常脚本由静态www池处理,阻塞脚本由动态io池处理
[www]
;名为www的进程池监听9000端口,常驻进程数量为固定4个
listen = 127.0.0.1:9000
pm = static
pm.max_children = 4
[io]
;名为io的进程池监听9001端口,进程数常驻4个,最大8个
listen = 127.0.0.1:9001
pm = dynamic
pm.max_children = 8
pm.start_servers = 4
pm.min_spare_servers = 4
pm.max_spare_servers = 4</code>
Copy after login

PHP-FPM main process is used to manage these working processes. For example, if a working process is killed, immediately recreate one.
PHP-FPM provides pm.status_path to view the work of the entire PHP-FPM service through the browser Status.
Such as execution timeout and giving up, automatically restarting the worker process after processing the specified number of requests, slow logging (finding out time-consuming files and functions) are all supported.

And after enabling persistent connections, each PHP-FPM working process can maintain a long connection to MySQL without releasing it, avoiding repeated connections to the database.
For example, the figure below shows two PHP-FPM processes and two MySQL connections. Long connection:
I don't quite understand the operating mechanism of PHP. Please give me a solution.
In addition, the PECL extension for Memcached and Redis also implements the function of persistent connection.

The PHP-FPM system is mentioned above, now let’s talk about the life cycle of PHP scripts under the PHP-FPM system.
The life cycle of the quantities in the PHP script (including global variables) only exists within one request, and the request is processed Once completed, PHP-FPM will automatically release the resources.
Resources are released once per request. This kind of memory release is very thorough. PHP's GC based on reference counting has ended before the program has even taken effect.
The release of resources here refers to It is the resource controlled in the script, and will not interfere with the PHP-FPM resident process, will not let the PHP-FPM process shut down, and will not let PHP-FPM close the persistent connection to MySQL. PHP-FPM is only responsible for inputting the PHP script. , to perform PHP operations, if ZendOpcache support is added, all opcodes generated by parsing PHP scripts can be cached in memory for direct interpretation and execution next time. PHP7 also supports using opcache.file_cache to export script opcodes to achieve source code protection.

Some common sense about PHP:
Database connection pool: PHP persistent connection is a natural and transparent connection pool that does not require program intervention, supporting MySQL/Memcached/Redis, etc.
Memory resident: PHP-FPM process, ZendOpcache cached script opcode , Yac developed by Brother Niao is all memory-resident.
Garbage collection: PHP-FPM’s operating mode of releasing resources once per request weakens the role of GC based on reference counting.

Finally, PHP daemon services such as Swoole/WorkerMan that work under CLI are similar to Java/Node.

Although I have already got off work, I couldn’t bear it when I saw that PHP is similar to html. The functions of PHP are incomparable to those of html. Take your example of connecting to a database, can html connect data? Can I read the contents of the database? No way! Also, you said that each user needs to open a database connection to access multiple users. You are looking down on PHP. Encapsulating a database connection class is very simple, so I won’t post the code. Each database extension in the PHP manual has an introduction and examples for your own reference. Since you mentioned java, you must also know the singleton pattern! PHPEncapsulate a database connection class and set up singleton mode to achieve static data connection. No matter how many users come to visit, just call it directly and you can open multiple processes instead of multiple users coming to visit as you said. And the setInterval and setTimeout you mentioned are not scheduled executions! PHP is also available! First define the functions to be implemented by PHP, and then set crontab on the server. Just set the parameters yourself, or php-fpm. I won’t list the functions, etc., and I haven’t formatted the answers yet, so you can take a look at them first. I have to get off work and leave. If we have any questions, we can continue discussing them tomorrow

In short, PHP is a very good language with very powerful functions... and it is still developing and growing... easy to learn and understand! Brother

PHP cannot reside in memory. After each HTTP request is opened, it connects to the database. When the request ends, the database connection and various variables are released.

Your overall understanding is correct, but not all languages ​​​​are memory-resident like java, neither python, go, nor c. PHP does not have the concept of a connection pool. The process will be released after it is executed and will not be left for other processes to use

Here is the link to the first section of Chapter 2 of "In-depth Understanding of the PHP Core":

http://www.php-internals.com/...

Your doubts are just because you only saw the surface.

If you have used swoole, I think you will not ask this question.

Uh, you thought php-fpm didn’t arrive. . .

And PHP doesn’t seem to be a program, it’s more similar to html

PHP can only be embedded into HTML, but it is completely different from HTML. PHP has many extensions that can do different things. Can HTML do it?

It will only be executed when it is opened. When no one accesses the PHP service, PHP will not occupy even a little bit of memory or a little bit of CPU. Is that right?

PHP mainly has two running modes (except CLI):
1. Mod_php represented by Apache, at this time the work is handed over to Apache.
2.php-fpm (fastcgi process manager) used by Nginx/Lighttpd, this is a resident daemon process.
So, how can it not occupy CPU and memory?

If this is the case, isn’t it difficult for PHP to encapsulate database classes? Because each user comes in and has to open a process for him, and the processes are not connected to each other. User A comes in and opens a database connection for him, and user B comes in and opens a separate database connection for him. So isn't PHP constantly connecting and disconnecting from the database? After there are more users, the overhead should be very high, right?

Take MySQL as an example. If you select pconnect (persistent connection) when connecting, the existing connection will be used directly next time and the connection will not be closed.
PDO also has a long connection option.

Is this also the reason why php does not have js-like setInterval or setTimeout functions?

PHP has delay functions (such as sleep()), and the accuracy is much higher than that of JS (microsecond level).

It’s so lively. @ivanilla's answers and comments contain a lot of information, thank you.

In fact, I think that in response to the original poster’s question, the operating mechanism of PHP is to interpret and execute scripts. PHP is a scripting language that provides server-side support for small and medium-sized websites. It has a good balance between development speed and operating efficiency. This is the reason for its success.

So the poster’s other views are of little value, and even the debate is meaningless. If PHP has the things you imagine, no one will use this language, and everyone might as well use Java.

The author does not know some basic knowledge of PHP. He should be new to PHP. To put it simply, PHP can be run in two modes. One is a script mode, such as executing php xxx.php in the shell; the other is to start running only when there is a network request (not very appropriate), and some are compiled into apache. Extension mode, there is also fast-cgi mode. Apache's mod_php method is to start a process for execution with a request. It is very efficient and has various parameter optimizations accordingly. Fast-cgi is much more efficient. Specific posters can read the corresponding manual and practice it.

The guys upstairs are so patient

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles