Home Backend Development PHP Tutorial The composition and types of PHP variables

The composition and types of PHP variables

Jun 05, 2018 pm 04:44 PM
php kernel

This article mainly introduces the composition and types of PHP variables. Interested friends can refer to it. I hope it will be helpful to everyone.

php variable components:

Variable name: The variable name in PHP language starts with $ in English/underscore, and can contain numbers, underscores, Letters, case sensitive. At the same time, PHP also supports compound variables, in the shape of $$A, which increases the dynamics of PHP.

Type: PHP is a weakly typed language and can assign any type of value.

Content: There can only be one value at the same time.

There are 8 data types in the PHP language, divided into three major categories:

1. Scalar types: Boolean, integer, float, string;

2. Composite types: object, array;

3. Special types: NULL, resource;

As a weakly typed language, PHP implements all Variables store data through the structure zval, which not only contains the value of the variable, but also the type of the variable, which is the core of PHP's weak typing.

zval data structure:

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

Zvalue_value is not a structure. In order to save memory, it is implemented using union, because the variable can only represent one type at the same time. Its prototype:

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

Hash table:

Many implementations inside PHP are based on hash tables: variable scope, function table, class attributes, methods, etc. A lot of data inside the Zend engine is stored in hash tables.

php arrays use hash tables to store associated data. The hash table implementation uses two data structures, HashTable and 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

The expansion of capacity in HashTable is always adjusted to the integer power of 2 close to the initial size. Because:

When selecting slots, the & operation is used instead of modulo. This is because the modulo operation is relatively more expensive than the bitwise AND operation. The function of the mask is to map the hash value to the index range that the slot can store. For example: the index value of a certain key is 21, the size of the hash table is 8, then the mask is 7, and the binary representation of the sum is: 10101 & 111 = 101, which is 5 in decimal. Because the binary system of 2 to the power of an integer -1 is special: the values ​​of the next N bits are all 1, which makes it easier to map the values. If it is an ordinary number and is combined in binary, it will affect the result of the hash value. Then the average distribution of values ​​calculated by the hash function may be affected.

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

The hash value is stored in the Bucket instead of the hash index.

The last field of the above structure is used to save the key string, but this field is declared as an array of only one character. In fact, this is a common variable-length structure. The main purpose is Increase flexibility. The following is the code for applying for space when inserting new elements into the hash table

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

Insertion process diagram

Hash algorithm

The hash function in php is implemented using the DJBX33A algorithm.

Object:

php objects are stored using the data structure zend_object_value;

Summary: The above is the entire content of this article, I hope it can be helpful to everyone learning helps.

Related recommendations:

Analysis of CURL examples of data transmission in PHP

Sharing of simple examples of adding data to xml files in PHP

Example of website directory scanning index tool based on PHP

The above is the detailed content of The composition and types of PHP variables. For more information, please follow other related articles on the PHP Chinese website!

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks 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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1248
24
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.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

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.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

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.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles