PHP kernel exploration: variable storage and type

Source: Internet
Author: User
Tags php language sapi variable scope value store

Answer the question in the previous section first.

01 <? Php
02 $ foo = 10;
03 $ bar = 20;
05 functionchange () {
06 global $ foo;
07 // echo ‘$ foo inside function =‘. $ Foo. ’<br />‘;
08 // If $ bar is not defined as a global variable, the function body cannot access $ bar
09 $ bar = 0;
10 $ foo ++;
13 change ();
14 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, and the value of $foo after increment is 11.

The role of global is to define globals, but this global variable is not applied to the entire site, but to the current page, including all files of include or require.

The preface mentions three basic characteristics of a variable, one of which is the type of the variable, and the variable has a specific type, such as: String, Array, object, and so on. The type system of a programming language can be divided into two types: strong and weak.

A strongly typed language is when a variable is declared to be a variable of a type, it is not possible to assign a value other than the type of the variable to it while the program is running (this is not entirely true, this may involve the conversion of the type, which is described later in the section), and C/c++/java and other languages fall into this category.

Scripting languages such as PHP and Ruby,javascript are weak-type languages: A variable can represent any data type.

PHP has become a simple and powerful language, and a large part of it is because it has weak-type variables. But sometimes this is also a double-edged sword, improper use will also bring some problems. Just like the instrument, the more powerful it is, the greater the likelihood of error.

Within the official PHP implementation, all variables are saved using the same data structure (Zval), which represents a variety of 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 type.

The ZVAL structure specifically how to achieve the weak type, we will come together to uncover the veil.

Variable storage structure

When you declare or use a variable, PHP does not need to explicitly indicate its data type.

PHP is a weakly typed language, which does not mean that PHP has no type, in PHP, there are 8 types of variables, can be divided into three categories

    • * Scalar type:boolean,integer,float (double),string
    • * Composite type: array,object
    • * Special Type: resource,NULL

The official PHP is implemented in C, and C is a strong type of language, how does this implement the weak type in PHP?

The value of the variable is stored in the ZVAL structure as shown below. The ZVAL structure is defined in the Zend/zend.h file, and its structure is as follows:

1	typedefstruct_zval_struct zval;
2	...
3	struct_zval_struct {
4	    /* Variable information */
5	    zvalue_value value;     /* value */
6	    zend_uint refcount__gc;
7	    zend_uchar type;    /* active type */
8	    zend_uchar is_ref__gc;
9	};

PHP uses this structure to store all the data for a variable. Unlike other compiled static languages, PHP stores variable types of PHP user space in the same structure when storing variables. This allows us to obtain the type of the variable through this information.

There are four fields in the Zval structure, which have the following meanings:

Property name meaning Default Value
refcount__gc Represents a reference count 1
is_ref__gc Indicates whether it is a reference 0
Value Value of the stored variable
Type Variable-specific type

After PHP5.3, a new garbage collection mechanism was introduced, with reference counts and referenced field names changed to REFCOUNT__GC and IS_REF__GC. Before this is refcount and is__ref.

The value of the variable is stored in another struct zvalue_value. The value store is described below.

PHP user space refers to the level of the PHP language, and most of the book is about the implementation of PHP. These implementations can be understood as kernel space. Since PHP is implemented in C, the scope of this space is limited to the C language. PHP User space is limited by the PHP syntax and functionality provided by the scope. For example, some PHP extensions provide PHP functions or classes, which are the methods or classes that are exported to the PHP user space.

Variable type

The Type field of the Zval struct is the most critical field that implements the weak type, and the value of type can be: Is_null, Is_bool, Is_long, is_double, is_string, Is_array, Is_object, and Is_ One of the RESOURCE. It's literally good to understand that they are just types of unique indicators that store different values in the Value field depending on the type. In addition, the types that are defined with them are is_constant and Is_constant_array.

This is similar to what we did when we designed the database, in order to avoid repeating the design of similar tables, using an indicator field to record different types of data.

The value of the variable is stored

The values of the variables mentioned above are stored in the Zvalue_value union, and the structure is defined as follows:

01	typedefunion_zvalue_value {
02	    longlval;                  /* long value */
03	    doubledval;                /* double value */
04	    struct{
05	        char*val;
06	        intlen;
07	    } str;
08	    HashTable *ht;              /* hash table value */
09	    zend_object_value obj;
10	} zvalue_value;

The use of a consortium instead of a struct is a consideration for space utilization, because a variable can only belong to one type at a time. If you use structs, you will waste space unnecessarily, and all of the logic in PHP is going around variables, so memory waste will be huge. The cost of this approach is small but the benefits are very large.

Various types of data use different methods to store variable values, and their corresponding assignments are as follows:

1. General type

Variable Type Macro ?
Boolean Zval_bool The value of a Boolean/integer variable is stored in the (zval). Value.lval, its type is also stored in the corresponding is_*.
Z_type_p (z) =is_bool/long;  
Integer Zval_long
Float Zval_double
Null Zval_null The variable value of the NULL value does not need to be stored, just the (zval). Type is labeled Is_null.
Resource Zval_resource The storage of resource types is the same as other general variables, but its initialization and access implementations are different.
Z_type_p (z) = Is_resource;  

2. String sting

The type of the string is the same as other data types, but there is one more string-length field when storing the string.

1	struct{
2	    char*val;
3	    intlen;
4	} str;

The string in C is an array of characters ending in a., where the length of the string is stored, which is the same as the redundant fields we added when designing the database. Because the time complexity to get the length of a string in real time is O (n), and the operation of the string is very frequent in PHP, it avoids the repetition of the length of the string, which can save a lot of time and is a space-time approach. So the strlen () function in PHP can get the length of a string in constant time. There are many strings in the computer language, so the length of the string is stored in most high-level languages.

3. Array of arrays

Arrays are the most commonly used and most powerful variable types in PHP, which can store other types of data and provide a variety of built-in manipulation functions. The storage of an array is more complex than other variables, and the value of the array is stored in the field, which is a hashtable type of data. An array of PHP uses a hash table to store the associated data. A hash table is an efficient storage structure for key-value pairs. PHP's hash table implementation uses two data structures hashtable and buckets. All of PHP's work is implemented by a hash table, and the basic concept of hash table is introduced in the next section Hashtable and the PHP hash table is implemented.

4. Object

In object-oriented languages, we can define our own data types, including the properties of classes, methods, and so on. The object is a concrete implementation of the class. The object has its own state and the actions it can accomplish.

The object of PHP is a compound type of data, which is stored using a zend_object_value structure. It is defined as follows:

1	typedefstruct_zend_object_value {
2	    zend_object_handle handle;  //  unsigned int type,EG(objects_store).object_buckets的索引
3	    zend_object_handlers *handlers;
4	} zend_object_value;

PHP objects are created only at run time, and the previous section describes the eg macro, which is a global structure used to hold data at run time. This includes the object pool used to hold all the objects created, EG (Objects_store), and the Zend_object_handle field of the object value content is the index of the current object in the object pool. The Handlers field is a handler that saves the object when it is manipulated. The structure of the struct and object-related classes is _zend_class_entry, which is described later.

PHP's weak-variable containers are implemented in an inclusive form, with their corresponding tags and storage space for each type of variable. Using strongly typed languages is often more efficient than weak types, because much of the information can be determined before it is run, which can also help eliminate program errors. The problem is that writing code is relatively constrained.

The main purpose of PHP is as a web development language, where bottlenecks in common Web applications are typically at the level of business and data access. But language can also be a key factor in large-scale applications. Facebook has therefore used its own PHP implementation. Compile PHP into C + + code to improve performance. But Facebook's hiphop is not a complete PHP implementation, because it compiles PHP directly into C + +, some PHP dynamic features such as the eval structure can not be implemented. Of course, there is a way to achieve, hiphop not realize should also do a trade-off.

Extended Reading

The list of topics for this article is as follows:

  1. PHP Kernel Explorer: Starting with the SAPI interface
  2. PHP kernel exploration: Start and end of a single request
  3. PHP kernel exploration: One-time request life cycle
  4. PHP Kernel Exploration: single-process SAPI life cycle
  5. PHP kernel Exploration: SAPI lifecycle of multiple processes/threads
  6. PHP Kernel Explorer: Zend Engine
  7. PHP Kernel Explorer: Explore SAPI again
  8. PHP kernel Discovery: Apache module Introduction
  9. PHP Kernel Explorer: PHP support via MOD_PHP5
  10. PHP kernel exploration: Apache Run with hook function
  11. PHP Kernel Explorer: embedded PHP
  12. PHP Kernel Explorer: PHP fastcgi
  13. PHP kernel exploration: How to execute PHP scripts
  14. PHP Kernel Explorer: PHP script execution details
  15. PHP kernel exploration: opcode opcode
  16. PHP kernel Explorer: PHP opcode
  17. PHP kernel exploration: Interpreter execution process
  18. PHP Kernel Exploration: Variables overview
  19. PHP kernel exploration: variable storage and type
  20. PHP Kernel Explorer: Hash table in PHP
  21. PHP Kernel Exploration: Understanding the hash table in Zend
  22. PHP kernel exploration: PHP hash Algorithm design
  23. PHP kernel Exploration: translating an article hashtables
  24. PHP Kernel exploration: What is a hash collision attack?
  25. PHP Kernel exploration: implementation of constants
  26. PHP kernel exploration: Storage of variables
  27. PHP kernel exploration: Types of variables
  28. PHP Kernel Explorer: Variable value operation
  29. PHP Kernel exploration: Creation of variables
  30. PHP kernel exploration: pre-defined variables
  31. PHP Kernel Explorer: variable retrieval
  32. PHP kernel Exploration: Variable type conversion
  33. PHP Kernel exploration: implementation of weakly typed variables
  34. PHP Kernel exploration: implementation of static variables
  35. PHP Kernel Explorer: Variable type hints
  36. PHP kernel exploration: The life cycle of a variable
  37. PHP Kernel Exploration: variable assignment and destruction
  38. PHP Kernel exploration: variable scope
  39. PHP kernel Explorer: Weird variable names
  40. PHP Kernel Explorer: variable value and type storage
  41. PHP Kernel Explorer: global variables
  42. PHP kernel Exploration: Conversion of variable types
  43. PHP kernel Exploration: The memory management begins
  44. PHP Kernel Explorer: Zend Memory manager
  45. PHP Kernel Explorer: PHP's memory management
  46. PHP Kernel Exploration: Application and destruction of memory
  47. PHP Kernel Exploration: reference count vs. write-time replication
  48. PHP kernel exploration: PHP5.3 garbage collection mechanism
  49. PHP Kernel Explorer: Cache in memory management
  50. PHP Kernel Exploration: write-time copy cow mechanism
  51. PHP kernel Exploration: arrays and Linked lists
  52. PHP kernel exploration: Using the Hash Table API
  53. PHP kernel exploration: array manipulation
  54. PHP kernel Exploration: Array source code Analysis
  55. PHP Kernel Exploration: Classification of functions
  56. PHP kernel Exploration: internal structure of functions
  57. PHP Kernel exploration: function structure transformation
  58. PHP Kernel Exploration: The process of defining a function
  59. PHP kernel Exploration: Parameters for functions
  60. PHP kernel exploration: zend_parse_parameters function
  61. PHP Kernel exploration: function return value
  62. PHP kernel exploration: formal parameter return value
  63. PHP Kernel exploration: function invocation and execution
  64. PHP kernel exploration: Referencing and function execution
  65. PHP kernel exploration: anonymous functions and closures
  66. PHP Kernel Exploration: object-oriented opening
  67. PHP kernel Exploration: The structure and implementation of classes
  68. PHP kernel exploration: member Variables for classes
  69. PHP Kernel Exploration: Member Methods for classes
  70. PHP Kernel Exploration: class prototype Zend_class_entry
  71. PHP kernel exploration: Definition of class
  72. PHP Kernel Explorer: Access control
  73. PHP kernel exploration: inheritance, polymorphism and abstract classes
  74. PHP Kernel Exploration: magic function and delay binding
  75. PHP kernel Exploration: Preserving classes and special classes
  76. PHP Kernel Explorer: objects
  77. PHP kernel Exploration: Creating object instances
  78. PHP Kernel Explorer: Object properties Read and write
  79. PHP Kernel Exploration: namespaces
  80. PHP kernel exploration: Defining interfaces
  81. PHP kernel Exploration: Inheritance and Implementation interface
  82. PHP Kernel Exploration: resource resource type
  83. PHP Kernel Explorer: Zend virtual machine
  84. PHP Kernel Exploration: Lexical parsing of virtual machines
  85. PHP Kernel Explorer: virtual machine Syntax analysis
  86. PHP kernel exploration: Execution of intermediate code opcode
  87. PHP Kernel Exploration: Code encryption and decryption
  88. PHP kernel exploration: zend_execute specific execution process
  89. PHP kernel exploration: Reference and counting rules for variables
  90. PHP kernel exploration: New garbage collection Mechanism description

PHP kernel exploration: variable storage and type

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.