C language Structure (struct): Contains multiple members, there may be multiple data types, and there are several types of space that need to be allocated to occupy space.
Union: Multiple types are supported for the consumer to use one of the data types, and of course the size of the data type in which the space is most occupied.
Structures and unions are usually present in a piece.
PHP is implemented in C, so think about why PHP can implement a weak type?
The answer lies in the structure and union of the C language.
Writes and reads from weakly typed variables are analyzed:
With the Union, we can define several types, let PHP variables in the selection, this can solve the variable write. So how do you solve reading this variable? After the variable is set, it is not known which type of union the variable is using and cannot be read.
You can set a member in a structure that specifically records which type is used in the Union. This will be OK.
Demonstrate with a simple C example: only three types are used here, integer floating-point numbers and strings, and PHP arrays are used hashtable here.
#include <stdio.h>typedef Union uval{LongA; Doubleb; Char*C;} Uval;typedefstructpval{Uval Val; intPhptype;} PVal;//enumvoidVar_dump (pval);intMain () {pval pval1= {{. A =111},1}; Var_dump (PVAL1);//int 111Pval1.phptype=2; PVAL1.VAL.B=1.21; Var_dump (PVAL1);//float 1.210000Pval1.phptype=3; PVAL1.VAL.C="ABC"; Var_dump (PVAL1);//string ABC}/** * @param val * Depending on the type of pval variable, decide to read that type of union*/voidVar_dump (PVal val) {if(Val.phptype = =1) {printf ("%s","int"); printf ("%ld\n", VAL.VAL.A); } Else if(Val.phptype = =2) {printf ("%s","float"); printf ("%f\n", val.val.b); } Else if(Val.phptype = =3) {printf ("%s","string"); printf ("%s\n", VAL.VAL.C); }}
It can be thought that this type of pval is the type of a variable in PHP. Each PHP variable records the value Val and the type Phptype (the actual reference count, etc.).
Each time a Val is written, its type is also recorded. This implements the weak type.
The structure and union of C languages, and how PHP implements weak types