PHP内核探索:变量存储与类型使用说明
这篇文章主要介绍了PHP内核探索:变量存储与类型的相关资料,需要的朋友可以参考下
先回答前面一节的那个问题吧。
复制代码 代码如下:
$foo = 10;
$bar = 20;
function change() {
global $foo;
//echo '函数内部$foo = '.$foo.'
';
//如果不把$bar定义为global变量,函数体内是不能访问$bar的
$bar = 0;
$foo++;
}
change();
echo $foo, ' ', $bar;
?>
程序输出 11 20。原因是,方法内部无法访问$bar变量,所以它的值还是20。使用global之后,可以取得$foo的值,自增后$foo的值就是11。
Global的作用是定义全局变量,但是这个全局变量不是应用于整个网站,而是应用于当前页面,包括include或require的所有文件。
前言中提到变量的三个基本特性,其中的有一个特性为变量的类型,变量都有特定的类型, 如:字符串、数组、对象等等。编程语言的类型系统可以分为强类型和弱类型两种:
强类型语言是一旦某个变量被申明为某个类型的变量,则在程序运行过程中,该不能将该变量的类型以外的值赋予给它 (当然并不完全如此,这可能会涉及到类型的转换,后面的小节会有相应介绍),C/C++/Java等语言就属于这类。
PHP及Ruby,JavaScript等脚本语言属于弱类型语言:一个变量可以表示任意的数据类型。
PHP之所以成为一个简单而强大的语言,很大一部分的原因是它拥有弱类型的变量。 但是有些时候这也是一把双刃剑,使用不当也会带来一些问题。就像仪器一样,越是功能强大, 出现错误的可能性也就越大。
在官方的PHP实现内部,所有变量使用同一种数据结构(zval)来保存,而这个结构同时表示PHP中的各种数据类型。 它不仅仅包含变量的值,也包含变量的类型。这就是PHP弱类型的核心。
那zval结构具体是如何实现弱类型的呢,下面我们一起来揭开面纱。
变量存储结构
PHP在声明或使用变量的时候,并不需要显式指明其数据类型。
PHP是弱类型语言,这并不表示PHP没有类型,在PHP中,存在8种变量类型,可以分为三类
* 标量类型:boolean、integer、float(double)、string
* 复合类型: array、object
* 特殊类型: resource、NULL
官方PHP是用C实现的,而C是强类型的语言,那这是怎么实现PHP中的弱类型的呢?
变量的值存储到以下所示zval结构体中。 zval结构体定义在Zend/zend.h文件,其结构如下:
复制代码 代码如下:
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使用这个结构来存储变量的所有数据。和其他编译性静态语言不同, PHP在存储变量时将PHP用户空间的变量类型也保存在同一个结构体中。这样我们就能通过这些信息获取到变量的类型。
zval结构体中有四个字段,其含义分别为:
属性名 含义 默认值
refcount__gc 表示引用计数 1
is_ref__gc 表示是否为引用 0
value 存储变量的值
type 变量具体的类型
在PHP5.3之后,引入了新的垃圾收集机制,引用计数和引用的字段名改为refcount__gc和is_ref__gc。在此之前为refcount和is__ref。
而变量的值则存储在另外一个结构体zvalue_value中。值存储见下面的介绍。
PHP用户空间指的在PHP语言这一层面,而本书中大部分地方都在探讨PHP的实现。 这些实现可以理解为内核空间。由于PHP使用C实现,而这个空间的范畴就会限制在C语言。 而PHP用户空间则会受限于PHP语法及功能提供的范畴之内。 例如有些PHP扩展会提供一些PHP函数或者类,这就是向PHP用户空间导出了方法或类。
变量类型
zval结构体的type字段就是实现弱类型最关键的字段了,type的值可以为: IS_NULL、IS_BOOL、IS_LONG、IS_DOUBLE、IS_STRING、IS_ARRAY、IS_OBJECT和IS_RESOURCE 之一。 从字面上就很好理解,他们只是类型的唯一标示,根据类型的不同将不同的值存储到value字段。 除此之外,,和他们定义在一起的类型还有IS_CONSTANT和IS_CONSTANT_ARRAY。
这和我们设计数据库时的做法类似,为了避免重复设计类似的表,使用一个标示字段来记录不同类型的数据。
变量的值存储
前面提到变量的值存储在zvalue_value联合体中,结构体定义如下:
复制代码 代码如下:
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. 一般类型
变量类型 宏 ?
boolean
ZVAL_BOOL
布尔型/整型的变量值存储于(zval).value.lval中,其类型也会以相应的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;

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics

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

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.

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.

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.

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

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

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++ 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.
