Table of Contents
PHP内核探索之变量,
您可能感兴趣的文章:
Home php教程 php手册 PHP内核探索之变量,

PHP内核探索之变量,

Jun 13, 2016 am 08:49 AM
php Kernel variable explore

PHP内核探索之变量,

php变量组成部分:

变量名:php语言的变量名以$开头+英文/下划线,可以包含数字、下划线、字母,区分大小写。同时PHP也支持复合变量,形如$$A,增加了php的动态性。

类型:php属于弱类型语言,可以赋值任意类型的值。

内容:在同一时刻只能有一种值。

php语言中存在8中数据类型,分为三大类:

1. 标量类型:Boolean,integer,float,string;

2. 复合类型:object,array;

3. 特殊类型:NULL,resource;

php作为一种弱类型语言,在实现内部所有变量是通过结构zval来存储数据的,不仅包含变量的值,也包含变量的类型,是php弱类型的核心。

zval数据结构:

struct _zval_struct{
  zvalue_value value;    //存储变量的值
  zend_unint  refcount_gc; //引用计数
  zend_char  is_ref_gc;  // 是否为引用
  zend_char  type;     //存储变量的类型
}
Copy after login

其中zvalue_value并不是一个结构体,为了节省内存使用的union来实现的,因为在同一时刻变量只能表示一种类型。其原型:

typedef union _zvalue_value{
  long lval;         
  double dval;
  struct {
      char *val;
      int len;      //字符串的长度
    }str;
  HashTable *ht;       //保存数组
  zend_object_value obj;   //对象
}zvalue_value;

Copy after login

哈希表:

php内部很多实现基于哈希表:变量的作用域、函数表、类的属性、方法等,Zend引擎内部的很多数据都是保存在哈希表中的。

php数组使用哈希表来存储关联数据,哈希表实现使用两个数据结构HashTable和Bucket:

HashTable:

typedef struct _hashtable { 
  uint nTableSize;    // hash Bucket的大小,最小为8,以2x增长。
  uint nTableMask;    // nTableSize-1 , 索引取值的优化
  uint nNumOfElements;  // hash Bucket中当前存在的元素个数,count()函数会直接返回此值 
  ulong nNextFreeElement; // 下一个数字索引的位置
  Bucket *pInternalPointer;  // 当前遍历的指针(foreach比for快的原因之一)
  Bucket *pListHead;     // 存储数组头元素指针
  Bucket *pListTail;     // 存储数组尾元素指针
  Bucket **arBuckets;     // 存储hash数组
  dtor_func_t pDestructor;  // 在删除元素时执行的回调函数,用于资源的释放
  zend_bool persistent;    // 指出了Bucket内存分配的方式。如果persisient为TRUE,
                  则使用操作系统本身的内存分配函数为Bucket分配内存,否则使用
                  PHP的内存分配函数。
  unsigned char nApplyCount; // 标记当前hash Bucket被递归访问的次数(防止多次递归)
  zend_bool bApplyProtection;// 标记当前hash桶允许不允许多次访问,不允许时,最多只能递归3次
#if ZEND_DEBUG
  int inconsistent;
#endif
} HashTable;
Copy after login

在HashTable中容量的扩增,始终调整为接近初始大小的2的整数次方。因为:

在选槽时,这里使用&操作而不是使用取模,这是因为是相对来说取模操作的消耗和按位与的操作大很多。mask的作用就是将哈希值映射到槽位所能存储的索引范围内。 例如:某个key的索引值是21, 哈希表的大小为8,则mask为7,则求与时的二进制表示为: 10101 & 111 = 101 也就是十进制的5。 因为2的整数次方-1的二进制比较特殊:后面N位的值都是1,这样比较容易能将值进行映射, 如果是普通数字进行了二进制与之后会影响哈希值的结果。那么哈希函数计算的值的平均分布就可能出现影响。

bucket:

typedef struct bucket {
  ulong h;      // 对char *key进行hash后的值,或者是用户指定的数字索引值
  uint nKeyLength;  // hash关键字的长度,如果数组索引为数字,此值为0
  void *pData;    // 指向value,一般是用户数据的副本,如果是指针数据,则指向pDataPtr
  void *pDataPtr;   //如果是指针数据,此值会指向真正的value,同时上面pData会指向此值
  struct bucket *pListNext;  // 整个hash表的下一元素
  struct bucket *pListLast;  // 整个哈希表该元素的上一个元素
  struct bucket *pNext;    // 存放在同一个hash Bucket内的下一个元素
  struct bucket *pLast;    // 同一个哈希bucket的上一个元素
// 保存当前值所对于的key字符串,这个字段只能定义在最后,实现变长结构体
  char arKey[1];       
} Bucket; 
Copy after login

在Bucket中存储的是哈希值而不是哈希的索引。

上面结构体的最后一个字段用来保存key的字符串,而这个字段却申明为只有一个字符的数组, 其实这里是一种长见的变长结构体,主要的目的是增加灵活性。 以下为哈希表插入新元素时申请空间的代码

p = (Bucket *) pemalloc(sizeof(Bucket) - 1 + nKeyLength, ht->persistent);
if (!p) {
  return FAILURE;
}
memcpy(p->arKey, arKey, nKeyLength);

Copy after login

插入过程图

哈希算法

php中hash函数使用DJBX33A算法来实现。

对象:

php对象使用数据结构zend_object_value来存储;

您可能感兴趣的文章:

  • php设计模式 Interpreter(解释器模式)
  • PHP设计模式之解释器模式的深入解析
  • PHP内核探索:变量存储与类型使用说明
  • PHP内核探索:变量概述
  • PHP内核探索:哈希表碰撞攻击原理
  • PHP内核探索之解释器的执行过程
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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1246
24
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,

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.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

See all articles