Home Backend Development PHP Tutorial PHP Kernel Research: HASH Table and Variables_PHP Tutorial

PHP Kernel Research: HASH Table and Variables_PHP Tutorial

Jul 14, 2016 am 10:08 AM
hash php Kernel variable and exist Attributes constant data Research kind surface

PHP HASH table

In PHP, all data, regardless of variables, constants, classes, and attributes, are implemented using Hash tables.
First let’s talk about the HASH table
typedef struct bucket {
ulong h;
uint nKeyLength; //key length
void *pData; //Pointer to the data saved by Bucke
void *pDataPtr; //Pointer data
struct bucket *pListNext; //Next element pointer
struct bucket *pListLast; //Previous element pointer
struct bucket *pNext;
struct bucket *pLast;
char arKey[1]; /* Must be last element */
} Bucket;
typedef struct _hashtable {
uint nTableSize;//Size of HashTable
uint nTableMask;//Equal to nTableSize-1
uint nNumOfElements;//Number of objects
ulong nNextFreeElement;//Points to the next empty element position nTableSize+1
Bucket *pInternalPointer; /* Used for element traversal *///Save the current traversed pointer
Bucket *pListHead;//Head element pointer
Bucket *pListTail;//Tail element pointer
Bucket **arBuckets;//Storage hash array data
dtor_func_t pDestructor;//Similar to the destructor
zend_bool persistent;//Which method to use to allocate memory space? PHP manages memory uniformly or uses ordinary malloc
unsigned char nApplyCount;//The number of times the current hash bucket has been accessed, whether the data has been traversed to prevent infinite recursive loops
zend_bool bApplyProtection;
#if ZEND_DEBUG
int inconsistent;
#endif
} HashTable;
Let’s combine it with the HASH table initialization function
ZEND_API int _zend_hash_init(HashTable *ht, uint nSize, hash_func_t pHashFunction, dtor_func_t pDestructor, zend_bool persistent ZEND_FILE_LINE_DC)
{
uint i = 3;
Bucket **tmp;
SET_INCONSISTENT(HT_OK);
if (nSize >= 0x80000000) { //If the HASH table size is greater than 0x8, it is initialized to 0x8
/* prevent overflow */
ht->nTableSize = 0x80000000;
} else {
while ((1U << i) < nSize) { //Adjust to the nth power of 2 i++; } } ht->nTableSize = 1 << i;//HASH bucket size is 2 The i power i=3, the minimum value of nTableSize is 8
}
//In order to improve calculation efficiency, the system will automatically adjust nTableSize to the smallest integer power of 2 that is not less than nTableSize. In other words, if you specify an nTableSize that is not an integer power of 2 when initializing HashTable, the system will automatically adjust the value of nTableSize
ht->nTableMask = ht->nTableSize - 1;
ht->pDestructor = pDestructor;//A function pointer, called when HashTable is added, deleted, or modified
ht->arBuckets = NULL;
ht->pListHead = NULL;
ht->pListTail = NULL;
ht->nNumOfElements = 0;
ht->nNextFreeElement = 0;
ht->pInternalPointer = NULL;
ht->persistent = persistent;//If persistent is TRUE, use the operating system's own memory allocation function to allocate memory for the Bucket, otherwise use PHP's memory allocation function
ht->nApplyCount = 0;
ht->bApplyProtection = 1;
/* Uses ecalloc() so that Bucket* == NULL */
if (persistent) { //The operating system allocates memory through its own memory allocation method. After calloc allocates memory, it is automatically initialized to 0
tmp = (Bucket **) calloc(ht->nTableSize, sizeof(Bucket *));
if (!tmp) {
return FAILURE;
}
ht->arBuckets = tmp;
} else {//Use PHP’s memory management mechanism to allocate memory
tmp = (Bucket **) ecalloc_rel(ht->nTableSize, sizeof(Bucket *));
if (tmp) {
ht->arBuckets = tmp;
}
}
//Automatically apply for a piece of memory for arBuckets, the memory size is equal to nTableSize
return SUCCESS;
}
When reading the source code, you will often see macros such as EG, PG, and CG
CG is the abbreviation of compile_global
EG is the abbreviation of excutor_global
G means global variable
Let’s take the EG macro as an example
#ifdef ZTS
# define EG(v) TSRMG(executor_globals_id, zend_executor_globals *, v)
#else
# define EG(v) (executor_globals.v)
extern ZEND_API zend_executor_globals executor_globals;
#endif
It’s very simple, just a macro to get global variables
Then let’s take a look at the zend_executor_globals structure
Defined in /Zend/zend.h
typedef struct _zend_executor_globals zend_executor_globals;
is an alias for _zend_executor_globals
Found it in the same file
All local variables, global variables, functions, and hash tables of classes in PHP are defined here
struct _zend_executor_globals {
zval **return_value_ptr_ptr;
zval uninitialized_zval;
zval *uninitialized_zval_ptr;
zval error_zval;
zval *error_zval_ptr;
zend_ptr_stack arg_types_stack;
/* symbol table cache */
HashTable *symtable_cache[SYMTABLE_CACHE_SIZE];
HashTable **symtable_cache_limit;
HashTable **symtable_cache_ptr;
zend_op **opline_ptr;
HashTable *active_symbol_table; //Local variables
HashTable symbol_table; /* main symbol table */ //Global variables
HashTable included_files; /* files already included */ //include files
JMP_BUF *bailout;
int error_reporting;
int orig_error_reporting;
int exit_status;
zend_op_array *active_op_array;
HashTable *function_table; /* function symbol table */ //Function table
HashTable *class_table; /* class table */ //Class table
HashTable *zend_constants; /* constants table */ //Constant table
zend_class_entry *scope;
zend_class_entry *called_scope; /* Scope of the calling class */
zval *This;
long precision;
int ticks_count;
zend_bool in_execution;
HashTable *in_autoload;
zend_function *autoload_func;
zend_bool full_tables_cleanup;
/* for extended information support */
zend_bool no_extensions;
#ifdef ZEND_WIN32
zend_bool timed_out;
OSVERSIONINFOEX windows_version_info;
#endif
HashTable regular_list;
HashTable persistent_list;
zend_vm_stack argument_stack;
int user_error_handler_error_reporting;
zval *user_error_handler;
zval *user_exception_handler;
zend_stack user_error_handlers_error_reporting;
zend_ptr_stack user_error_handlers;
zend_ptr_stack user_exception_handlers;
zend_error_handling_t error_handling; 
zend_class_entry *exception_class; 
  
/* timeout support */ 
int timeout_seconds; 
  
int lambda_count; 
  
HashTable *ini_directives; 
HashTable *modified_ini_directives; 
  
zend_objects_store objects_store; 
zval *exception, *prev_exception; 
zend_op *opline_before_exception; 
zend_op exception_op[3]; 
  
struct _zend_execute_data *current_execute_data; 
  
struct _zend_module_entry *current_module; 
  
zend_property_info std_property_info; 
  
zend_bool active; 
  
void *saved_fpu_cw; 
  
void *reserved[ZEND_MAX_RESERVED_RESOURCES]; 
}; 
 
 
 
这里先简单看看,以后用到的时候再细说,
 
PHP里最基本的单元 变量:
在PHP里 定义一个变量 再简单不过了
$a=1; 
?> 
 
但是在内核中 它是用一个 zval结构体实现的
如上面定义变量 在内核中则执行了下面这些代码
 
 
 
zval *val; 
MAKE_STD_ZVAL(val);  //申请一块内存 
ZVAL_STRING(val,"hello",1);//用ZVAL_STRING设置它的值为 "hello" 
ZEND_SET_SYMBOL(EG(active_symbol_table),"a",val));//将  val指针加入到符号表里面去 
宏 MAKE_STD_ZVAL 定义如下
 
 
 
#define MAKE_STD_ZVAL(zv)                                 
ALLOC_ZVAL(zv);  //它归根到底等于 (p) = (type *) emalloc(sizeof(type)) 
INIT_PZVAL(zv); 
INIT_PZVAL定义在
 
 
 
#define INIT_PZVAL(z)           看得出它是初始化参数 
(z)->refcount__gc = 1;   
(z)->is_ref__gc = 0; 
那么 zval到底是什么呢
在zend/zend.h里面
typedef struct _zval_struct zval; //原来它是 _zval_struct 的别名
_zval_struct 定义如下
 
 
 
typedef union _zvalue_value { 
        long lval;  //保存long类型的数据 
        double dval; //保存 double类型的数据 
        struct { 
                char *val; //真正的值在这里 
                int len;   //这里返回长度 
        } str; 
        HashTable *ht; 
        zend_object_value obj; //这是一个对象 
} zvalue_value; 
  
struct _zval_struct { 
zvalue_value value;             //保存的值 
zend_uint refcount__gc;//被引用的次数 如果为1 则只被自己使用如果大于1 则被其他变量以&的形式引用. 
zend_uchar type;       //数据类型 这也是 为什么 PHP是弱类型的原因 
zend_uchar is_ref__gc;  //表示是否为引用 
}; 
如果还是不够清楚..那么我们实战一下..用C来创建一个PHP变量
这里需要一个扩展,PHP如果用C扩展模块 这里就不说了
关键代码
 
 
 
PHP_FUNCTION(test_siren){ 
        zval *value; 
        char *s="create a php variable"; 
        value=(zval*)malloc(sizeof(zval)); 
        memset(value,0,sizeof(value)); 
        value->is_ref__gc=0; //非引用变量 
        value->refcount__gc=1;//引用次数 只有自己 
value->type=IS_STRING;//The type is string
value->value.str.val=s;//value
value->value.str.len=strlen(s);//length
ZEND_SET_SYMBOL(EG(active_symbol_table),"a",value);
}
The third and fourth lines have the same function as MAKE_STD_ZVAL, allocating memory space to value
The function of lines 5-9 is the same as that of ZVAL_STRING,
The last line is to create a variable called $a in PHP for value and add it to the local Hash table.
This way in PHP
test_siren(1);
echo $a;
?>
It will output “create a php variable”
OK,
Done
Note that I created variables in the form of C in order to let everyone see the process of creating variables inside PHP,
Absolutely not recommended for everyone to do this.
You must still use PHP’s internal memory management mechanism to allocate and process memory.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/477783.htmlTechArticlePHP HASH table In PHP, all data regardless of variables, constants, classes, and attributes are implemented using Hash tables . Let’s first talk about the HASH table typedef struct bucket { ulong h; /* Used for numeric indexing */ ui...
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

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

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

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,

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