文章插圖

文章插圖
說明
這里基于php7.2.5進行測試,php7之后內部結構變化應該不是太大,但與php5.X有差別 。
【php語法菜鳥教程 php語言基本知識】使用
變量聲明及使用
$a = "hello"; // stringecho is_string($a); // 1$b = 1; // intecho is_int($b); // 1$c = [1]; // array$d = true; // bool弱類型區別于C/JAVA/GO等強類型語言,PHP在聲明變量的時候不需要指定變量的類型,代碼在執行的時候會自動去解析變量的類型 。
如何實現
存儲變量的底層結構zval、zend_value(zend_types.h)
struct _zval_struct {zend_valuevalue;/* value 變量值放在這里 */union {struct {ZEND_ENDIAN_LOHI_4(zend_uchartype,/* active type 變量類型stirng/true/false/array */zend_uchartype_flags,zend_ucharconst_flags,zend_ucharreserved)/* call info for EX(This) */} v;uint32_t type_info;} u1;union {uint32_tnext;/* hash collision chain */uint32_tcache_slot;/* literal cache slot */uint32_tlineno;/* line number (for ast nodes) */uint32_tnum_args;/* arguments number for EX(This) */uint32_tfe_pos;/* foreach position */uint32_tfe_iter_idx;/* foreach iterator index */uint32_taccess_flags;/* class constant access flags */uint32_tproperty_guard;/* single property guard */uint32_textra;/* not further specified */} u2;};// zend_valuetypedef union _zend_value {zend_longlval;/* long value 這里存儲int的值 */doubledval;/* double value */zend_refcounted*counted; /* 引用計數 用于垃圾回收 */zend_string*str; /* 字符串 */zend_array*arr;zend_object*obj;zend_resource*res;zend_reference*ref;zend_ast_ref*ast;zval*zv;void*ptr;zend_class_entry *ce;zend_function*func;struct {uint32_t w1;uint32_t w2;} ww;} zend_value;// zval.u1.v1.type的類型的定義/* regular data types */#define IS_UNDEF0#define IS_NULL1 空 #define IS_FALSE2 false#define IS_TRUE3#define IS_LONG4#define IS_DOUBLE5#define IS_STRING6 字符串#define IS_ARRAY7#define IS_OBJECT8#define IS_RESOURCE9#define IS_REFERENCE10/* constant expressions */#define IS_CONSTANT11#define IS_CONSTANT_AST12/* fake types */#define _IS_BOOL13#define IS_CALLABLE14#define IS_ITERABLE19#define IS_VOID18/* internal types */#define IS_INDIRECT15#define IS_PTR17#define _IS_ERROR20我們可以先看一下zval.u1.v.type 與 zend_value其他的元素可以暫時忽略 。zval是存放變量的結構體,變量的值則放在zend_value中,zend_value是一個union類型,也就是共用體,特點就是可以存放多種類型的數據,但同時只有一個種類型可以有值 。
$a = "hello";那么PHP代碼在編譯、執行的時候通過詞法語法解析,將值1生成一個zval結構體,zval.u1.type就是IS_STRING類型,值存儲在zend_value中的str也就是zend_string中 。總結
弱類型的實現是基于zend_value共用體實現,變量類型在代碼解析的時候根據語法去解析生成的 。
- php反序列化函數 php序列化和反序列化
- mysql分頁語法 mysql分頁的幾種方式
- php時間代碼分秒 php時間函數代碼
- 免費php空間哪個好 支持php的免費空間
- html連接mysql數據庫PHP html連接mysql數據庫PHP后文件名是什么
- php導出excel php excel導入數據
- php函數的定義和調用 php調用類方法
- php判斷為空 php判斷數據庫值是否為空
- 目前流行的php開發工具有哪些 開發php用什么工具好
- php開發實例大全 php開發項目實戰
