


Wang Shuai: In-depth PHP kernel (1) - Exploring the principle of weakly typed variables
PHP is a simple and powerful language that provides many language features suitable for the Web, including weak typing of variables. Under the weak typing mechanism, you can assign any type of value to a variable.
PHP is executed through Zend Engine (hereinafter referred to as ZE). ZE is written in C and implements a set of weak type mechanisms at the bottom. ZE's memory management uses optimization strategies such as copy-on-write and reference counting to reduce memory copies when reassigning variables.
The following not only takes you to explore the principles of PHP weak typing, but also writes about PHP extensions and introduces how to operate PHP variables.
1. PHP variable types
There are 8 variable types in PHP:
- Standard types: boolean, integer, floating point float, string
- Complex types: array array, object
- Special type: resource
PHP does not strictly check the variable type. Variables can declare their type without displaying it, and assign values directly during runtime. Variables can also be converted freely. As in the following example, without implementation declaration, $i can be assigned any type of value.
[php] view plaincopy
- $i = 1; //int $i = 'show me the money'; //string $i = 0.02; //float $i = array( 1, 2, 3); // array $i = new Exception('test', 123); // object $i = fopen('/tmp/aaa.txt', 'a') // resource ?>
If you don’t have a deep understanding of the principle of weak typing, you will have “exceeding expectations” surprises when comparing variables.
[php] view plaincopy
- $str1 = null; $str2 = false; echo$str1 ==$str2 ? 'Equal' : 'Not equal'; $str3 = ''; $str4 = 0; echo $str3= =$str4 ? 'equal' : 'not equal'; $str5 = 0; $str6 = '0'; echo $str5==$str6 ? 'equal' : 'not equal'; ?>
All the above three results They are equal because PHP performs variable conversion internally when comparing variables. If you want the value and type to be determined at the same time, please use three = (for example, $a===0) to determine. Maybe you will find it commonplace, maybe you will find it amazing, then please join me to delve into the PHP kernel and explore the principle of PHP variables.
2. Introduction to variable storage and standard types
All variables in PHP are implemented with the structure zval. In Zend/zend.h we can see the definition of zval:
[php] view plaincopy
- typedef union _zvalue_value { long lval; /* long value */ double dval; /* dou ble value */ struct { char *val; int len; /* this will always be set for strings */ } str; /* string (always has length) */ HashTable *ht; /* an array */ zend_object_value obj; /* stores an object store handle, and handlers */}zvalue_value; means reference count
Indicates whether it is a reference | 0 | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
type | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Among them, refcount__gc and is_ref__gc indicate whether the variable is a reference. The type field identifies the type of the variable. The value of type can be: IS_NULL, IS_BOOL, IS_LONG, IS_FLOAT, IS_STRING, IS_ARRAY, IS_OBJECT, IS_RESOURCE. PHP chooses how to store zvalue_value based on the type. [php] view plaincopy
[php] view
plaincopy
5. Conversion of variable types Follow Now what we know about the PHP language, variables The type depends on the zval.type field indication, and the content of the variable is stored in zval.value according to zval.type. When variables are needed in PHP, only two steps are required: change the value or pointer of zval.value, and then change the type of zval.type. However, for some of PHP's advanced variables Array/Object/Resource, variable conversion requires more operations. Variable conversion principles are divided into 3 types: 5.1 Standard type mutual conversion is relatively simple, just follow the above steps for conversion. 5.2 Standard type and resource type conversion The resource type can be understood as int, which is more convenient for converting standard types. After conversion, the resource will be closed or recycled. [php] view plaincopy
5.3 Standard type and complex type conversion Array conversion int/floating point type Float will return the number of elements; conversion to bool will return whether there are elements in Array; conversion to string will return 'Array' and throw a warning. 5.4 Complex type mutual conversion array and object can be converted to each other. If any other type of value is converted to an object, an instance of the built-in class stdClass will be created. When we write PHP extensions, the PHP kernel provides a set of functions for type conversion:
A set of macros provided by the PHP kernel to conveniently access zval and obtain the value of zval in a more fine-grained manner:
6. Variable symbol table and scope PHP’s variable symbol table and zval value mapping is through HashTable (hash table, also called hash table, hereinafter referred to as HT). HashTable is widely used in ZE, including Language features such as constants, variables, and functions are organized by HT, and the array type in PHP is also implemented through HashTable. [php] view plaincopy The variable name of $var will be stored in the variable symbol table and represents $ The zval structure of the var's type and value is stored in a hash table. The kernel implements access to PHP variables through the hash mapping of the variable symbol table and the zval address. Why do we need to mention scope? Because the internal variables of the function are protected. According to the scope, PHP variables are divided into global variables and local variables. Each scope PHP maintains a HashTable of symbol tables. When creating a function or class in PHP, ZE will create a new symbol table to indicate that the variables in the function or class are local variables. This achieves the protection of local variables - variables inside the function cannot be accessed from the outside. When creating a PHP variable, ZE will assign a zval, set the corresponding type and initial value, and add the variable to the symbol table of the current scope so that the user can use the variable.
[php] view plaincopy
When writing a PHP extension, you can access PHP's variable symbol table through the EG macro. EG (symbol_table) accesses the variable symbol table of the global scope, and EG (active_symbol_table) accesses the variable symbol table of the current scope. The local variable stores a pointer, which is passed to the corresponding function when operating on the HashTable. In order to better understand the hash table and scope of variables, let’s take a simple example:
$temp =
|

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

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.


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

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

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Mac version
God-level code editing software (SublimeText3)

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

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.