Home Backend Development PHP Tutorial PHP Kernel Exploration: Variable Storage and Type Usage Instructions_PHP Tutorial

PHP Kernel Exploration: Variable Storage and Type Usage Instructions_PHP Tutorial

Jul 13, 2016 am 10:39 AM
variable storage type

Let’s answer the question in the previous section first.

Copy code The code is as follows:

$foo = 10;
$bar = 20;

function change() {
global $foo;
//echo 'Internal function $foo = '.$foo.'
';
/ /If $bar is not defined as a global variable, $bar cannot be accessed within the function body.
$bar = 0;
$foo++;
}

change (); echo $foo, ' ', $bar;
?>

Program output 11 20. The reason is that the $bar variable cannot be accessed inside the method, so its value is still 20. After using global, you can get the value of $foo. After the auto-increment, the value of $foo is 11.

Global is used to define global variables, but this global variable does not apply to the entire website, but to the current page, including all files in include or require.
The three basic characteristics of variables are mentioned in the preface. One of them is the type of variables. Variables have specific types, such as strings, arrays, objects, etc. The type system of programming languages ​​can be divided into two types: strong type and weak type:
Strongly typed language means that once a variable is declared as a variable of a certain type, the type of the variable cannot be changed during the running of the program. Values ​​other than other values ​​are assigned to it (of course, this is not entirely the case. This may involve type conversion, which will be introduced in the following sections). Languages ​​such as C/C++/Java fall into this category.
Script languages ​​such as PHP, Ruby, and JavaScript are weakly typed languages: a variable can represent any data type.
A large part of the reason why PHP has become a simple and powerful language is that it has weakly typed variables. But sometimes this is also a double-edged sword, and improper use can cause some problems. Just like an instrument, the more powerful it is, the greater the potential for error.
In the official PHP implementation, all variables are stored using the same data structure (zval), and this structure also represents various data types in PHP. It contains not only the value of the variable, but also the type of the variable. This is the core of PHP's weak typing.
So how does the zval structure implement weak types? Let’s uncover the veil together.
Variable storage structure
PHP does not need to explicitly indicate its data type when declaring or using variables.
PHP is a weakly typed language, which does not mean that PHP has no types. In PHP, there are 8 variable types, which can be divided into three categories
* Scalar types: boolean, integer, float (double), string
* Composite types: array, object
* Special types: resource, NULL
Official PHP is implemented in C, and C is a strongly typed language, so how does this implement weak typing in PHP? ?
The value of the variable is stored in the zval structure shown below. The zval structure is defined in the Zend/zend.h file, and its structure is as follows:

Copy code The code is as follows:
typedef struct _zval_struct zval;
...
struct _zval_struct {
/* Variable information */
zvalue_value value; /* value */
zend_uint refcount__gc;
zend_uchar type; /* active type */
zend_uchar is_ref__gc;
};

PHP uses this structure to store all data for variables. Unlike other compiled static languages, PHP also saves the PHP user space variable type in the same structure when storing variables. In this way we can obtain the type of the variable through this information.
There are four fields in the zval structure, their meanings are:

属性名 含义 默认值
refcount__gc 表示引用计数 1
is_ref__gc 表示是否为引用 0
value 存储变量的值
type 变量具体的类型

After PHP5.3, a new garbage collection mechanism was introduced, and the reference counting and referenced field names were changed to refcount__gc and is_ref__gc. Before that were refcount and is__ref.

The value of the variable is stored in another structure zvalue_value. Value storage is described below.
PHP user space refers to the level of PHP language, and most of this book discusses the implementation of PHP. These implementations can be understood as kernel space. Since PHP is implemented in C, the scope of this space will be limited to C language. The PHP user space will be limited to the scope of PHP syntax and functions provided. For example, some PHP extensions provide some PHP functions or classes, which export methods or classes to the PHP user space.
Variable type
The type field of the zval structure is the most critical field to implement weak typing. The value of type can be one of: IS_NULL, IS_BOOL, IS_LONG, IS_DOUBLE, IS_STRING, IS_ARRAY, IS_OBJECT and IS_RESOURCE. It's easy to understand literally. They are just unique identifiers of types, and different values ​​are stored in the value field according to different types. In addition, the types defined with them are IS_CONSTANT and IS_CONSTANT_ARRAY.
This is similar to what we do when designing a database. In order to avoid duplicating the design of similar tables, we use an indicator field to record different types of data.

The value of the variable is stored
As mentioned earlier, the value of the variable is stored in the zvalue_value union. The structure is defined as follows:

Copy code The code is as follows:

typedef union _zvalue_value {
long lval; /* long value */
double dval; /* double value */
struct {
char *val;
int len;
} str;
HashTable *ht; /* hash table value */
zend_object_value obj;
} zvalue_value;

这里使用联合体而不是用结构体是出于空间利用率的考虑,因为一个变量同时只能属于一种类型。 如果使用结构体的话将会不必要的浪费空间,而PHP中的所有逻辑都围绕变量来进行的,这样的话, 内存浪费将是十分大的。这种做法成本小但收益非常大。
各种类型的数据会使用不同的方法来进行变量值的存储,其对应赋值方式如下:

1. 一般类型

Variable type Macro ?
boolean ZVAL_BOOL Boolean/integer variable values ​​are stored in (zval).value.lval, and their types will also be stored with the corresponding IS_*.
Z_TYPE_P(z)=IS_BOOL/LONG; Z_LVAL_P(z)=((b)!=0);
integer ZVAL_LONG
float ZVAL_DOUBLE
null ZVAL_NULL NULL值的变量值不需要存储,只需要把(zval).type标为IS_NULL。
Z_TYPE_P(z)=IS_NULL;
resource ZVAL_RESOURCE 资源类型的存储与其他一般变量无异,但其初始化及存取实现则不同。
Z_TYPE_P(z) = IS_RESOURCE; Z_LVAL_P(z) = l;

2. String Sting
The type indication of string is the same as other data types, but there is an additional field for string length when storing strings.

Copy code The code is as follows:

struct {
char *val;
int len;
} str;

The character string in C starts with

3. Array

Array is the most commonly used and most powerful variable type in PHP. It can store other types of data and provides various built-in operation functions. The storage of arrays is more complicated than other variables. The value of the array is stored in the zvalue_value.ht field, which is a HashTable type data. PHP's arrays use hash tables to store associated data. A hash table is an efficient key-value pair storage structure. Two data structures, HashTable and Bucket, are used in PHP's hash table implementation. All the work of PHP is implemented by hash tables. In the next section HashTable, we will introduce the basic concepts of hash tables and the implementation of hash tables in PHP.

4. Object

In object-oriented languages, we can define the data types we need, including class attributes, methods and other data. An object is a specific implementation of a class. Objects have their own state and operations they can complete.

PHP’s object is a composite data, which is stored using a zend_object_value structure. Its definition is as follows:

Copy code The code is as follows:
typedef struct _zend_object_value {
zend_object_handle handle; // unsigned int type, EG( objects_store).object_buckets index
zend_object_handlers *handlers;
} zend_object_value;

PHP objects are only created at runtime. The previous chapter introduced the EG macro, which is a global structure used to save data at runtime. This includes the object pool used to save all created objects, EG (objects_store), and the zend_object_handle field of the object object value content is the index of the current object in the object pool, and the handlers field is the index when the object is operated. The processing function is saved. The structure _zend_class_entry of this structure and object-related classes will be introduced later.

PHP’s weak variable container is implemented in an inclusive form, and each type of variable has its corresponding tag and storage space. Languages ​​that use strong types are usually more efficient than weak types because a lot of information can be determined before running, which can also help eliminate program errors. The problem this brings is that writing code is relatively restricted.

PHP is mainly used as a web development language. In ordinary web applications, the bottleneck is usually at the business and data access layer. However, language will also be a key factor in large applications. Facebook therefore uses its own PHP implementation. Compile PHP to C++ code to improve performance. However, Facebook's hiphop is not a complete PHP implementation. Since it directly compiles PHP into C++, some dynamic features of PHP such as the eval structure cannot be implemented. Of course, there are ways to implement it. If hiphop does not implement it, it should be a trade-off.

http://www.bkjia.com/PHPjc/728099.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/728099.htmlTechArticleLet’s answer the question in the previous section first. Copy the code as follows: ?php $foo = 10; $bar = 20; function change() { global $foo; //echo 'Internal function $foo = '.$foo.'br /'; //If not. ..
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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)

How to change network type to private or public in Windows 11 How to change network type to private or public in Windows 11 Aug 24, 2023 pm 12:37 PM

Setting up a wireless network is common, but choosing or changing the network type can be confusing, especially if you don't know the consequences. If you're looking for advice on how to change the network type from public to private or vice versa in Windows 11, read on for some helpful information. What are the different network profiles in Windows 11? Windows 11 comes with a number of network profiles, which are essentially sets of settings that can be used to configure various network connections. This is useful if you have multiple connections at home or office so you don't have to set it all up every time you connect to a new network. Private and public network profiles are two common types in Windows 11, but generally

Implementing dynamic arrays in Python: from beginner to proficient Implementing dynamic arrays in Python: from beginner to proficient Apr 21, 2023 pm 12:04 PM

Part 1 Let’s talk about the nature of Python sequence types. In this blog, let’s talk about Python’s various “sequence” classes and the three built-in commonly used data structures – list, tuple and character. The nature of the string class (str). I don’t know if you have noticed it, but these classes have an obvious commonality. They can be used to save multiple data elements. The most important function is: each class supports subscript (index) access to the elements of the sequence, such as using SyntaxSeq[i]​. In fact, each of the above classes is represented by a simple data structure such as an array. However, readers familiar with Python may know that these three data structures have some differences: for example, tuples and strings cannot be modified, while lists can.

How to create a video matrix account? What types of matrix accounts do it have? How to create a video matrix account? What types of matrix accounts do it have? Mar 21, 2024 pm 04:57 PM

With the popularity of short video platforms, video matrix account marketing has become an emerging marketing method. By creating and managing multiple accounts on different platforms, businesses and individuals can achieve goals such as brand promotion, fan growth, and product sales. This article will discuss how to effectively use video matrix accounts and introduce different types of video matrix accounts. 1. How to create a video matrix account? To make a good video matrix account, you need to follow the following steps: First, you must clarify what the goal of your video matrix account is, whether it is for brand communication, fan growth or product sales. Having clear goals helps develop strategies accordingly. 2. Choose a platform: Choose an appropriate short video platform based on your target audience. The current mainstream short video platforms include Douyin, Kuaishou, Huoshan Video, etc.

What is the type of return value of Golang function? What is the type of return value of Golang function? Apr 13, 2024 pm 05:42 PM

Go functions can return multiple values ​​of different types. The return value type is specified in the function signature and returned through the return statement. For example, a function can return an integer and a string: funcgetDetails()(int,string). In practice, a function that calculates the area of ​​a circle can return the area and an optional error: funccircleArea(radiusfloat64)(float64,error). Note: If the function signature does not specify a type, a null value is returned; it is recommended to use a return statement with an explicit type declaration to improve readability.

Best practices for type hints in Python Best practices for type hints in Python Apr 23, 2023 am 09:28 AM

It’s great to use dynamic language for a while, and the code is reconstructed in the crematorium. I believe you must have heard this sentence. Like unit testing, although it takes a small amount of time to write code, it is very worthwhile in the long run. This article shares how to better understand and use Python's type hints. 1. Type hints are only valid at the syntax level. Type hints (introduced since PEP3107) are used to add types to variables, parameters, function parameters, and their return values, class properties, and methods. Python's variable types are dynamic and can be modified at runtime to add type hints to the code. It is only supported at the syntax level and has no impact on the running of the code. The Python interpreter will ignore the type hints when running the code. Therefore the type

C++ function types and characteristics C++ function types and characteristics Apr 11, 2024 pm 03:30 PM

C++ functions have the following types: simple functions, const functions, static functions, and virtual functions; features include: inline functions, default parameters, reference returns, and overloaded functions. For example, the calculateArea function uses π to calculate the area of ​​a circle of a given radius and returns it as output.

What are the main self-media platforms? What are the types of self-media platforms? What are the main self-media platforms? What are the types of self-media platforms? Mar 21, 2024 pm 06:36 PM

With the rapid development of the Internet, self-media has become an important channel for information dissemination. We-media platforms provide a stage for individuals and companies to showcase themselves and spread information. Currently, the main self-media platforms on the market include WeChat official accounts, Toutiao, Yidian News, Penguin Media Platform, etc. Each of these platforms has its own characteristics and provides a wealth of creative space for the majority of self-media practitioners. Next, we will introduce these platforms in detail and explore the types of self-media platforms. 1. What are the main self-media platforms? WeChat official account is a self-media platform launched by Tencent to provide information release and dissemination services for individual and corporate users. It is divided into two types: service account and subscription account. Service account mainly provides services for enterprises, while subscription account focuses on information dissemination. Depend on

An in-depth exploration of the storage location and mechanism of Golang variables An in-depth exploration of the storage location and mechanism of Golang variables Feb 28, 2024 pm 09:45 PM

Title: An in-depth exploration of the storage location and mechanism of Golang variables. As the application of Go language (Golang) gradually increases in the fields of cloud computing, big data and artificial intelligence, it is particularly important to have an in-depth understanding of the storage location and mechanism of Golang variables. In this article, we will discuss in detail the memory allocation, storage location and related mechanisms of variables in Golang. Through specific code examples, it helps readers better understand how Golang variables are stored and managed in memory. 1.Memory of Golang variables

See all articles