<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>风雪之隅 &#187; variable</title>
	<atom:link href="http://www.laruence.com/tag/variable/feed" rel="self" type="application/rss+xml" />
	<link>http://www.laruence.com</link>
	<description>PHP语言, PHP扩展, Zend引擎相关的研究,技术,新闻分享 - 左手代码 右手诗</description>
	<lastBuildDate>Wed, 08 Feb 2012 05:12:49 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1.2</generator>
		<item>
		<title>深入理解PHP原理之变量生命期(一)</title>
		<link>http://www.laruence.com/2009/12/26/1198.html</link>
		<comments>http://www.laruence.com/2009/12/26/1198.html#comments</comments>
		<pubDate>Sat, 26 Dec 2009 13:11:44 +0000</pubDate>
		<dc:creator>雪候鸟</dc:creator>
				<category><![CDATA[PHP源码分析]]></category>
		<category><![CDATA[GET]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[PHP应用]]></category>
		<category><![CDATA[SAPI]]></category>
		<category><![CDATA[variable]]></category>

		<guid isPermaLink="false">http://www.laruence.com/?p=1198</guid>
		<description><![CDATA[对于PHP的中的数据来源, 不外乎有俩种:
<coolcode lang="sh" linenum="off">
1. 来自代码中
2. 来自外部(GET/POST/DB)
</coolcode>
	
	对于代码中的变量(也就是直接量)来说, 变量分配/赋值在编译期, 活跃在执行器, 在请求关闭期被销毁.对于这些变量来说, 使用APC进行Opcode缓存, 则会缓存这部分变量的值. 

	而对于来自外部的变量, 变量分配/赋值在编译器后, 执行期前, 在请求关闭期被销毁,对于这些变量来说, 使用APC进行OpCode缓存, 是不会被缓存的.

	今天就着重关注下外部变量的一个部分,GET来的数据的整个生命周期....]]></description>
			<content:encoded><![CDATA[<div class="copyright" >
<ul  style="padding-left:1em;font-size:85%;padding-left:1em;font-size:85%;">
<li>作者: <a href="http://www.laruence.com" >Laruence</a>(<a href="http://www.twitter.com/laruence"  target="meme"  title="Twitter" ><img src="/images/ico-twitter.png" /></a> <a href="http://t.sina.com/laruence"  target="meme"  title="新浪微博" ><img src="/images/ico-sina.png" /></a> <a href="http://fusion.google.com/add?feedurl=http://www.laruence.com/feed"  target="meme"  title="Google阅读器" ><img src="/images/ico-google.png" /></a> <a href="mailto:laruence@yahoo.com.cn"  target="meme"  title="邮件" ><img src="/images/ico-mail.png" /></a>)</li>
<li>本文地址: <a href="http://www.laruence.com/2009/12/26/1198.html"  title="Permanet Link to 深入理解PHP原理之变量生命期(一)" >http://www.laruence.com/2009/12/26/1198.html</a></li>
</li>
<li>转载请注明出处 </li>
</ul></div>
<p>
	对于PHP的中的数据来源, 不外乎有俩种:</p>
<pre name="code"  class="sh_sh"  linenum="off"   style="background: #333; color: #d9d9d9; border-left: 15px solid #c9c9c9; padding: 9px; font-size: 1em; overflow-x: auto;font-family:Monacobackground: #333; color: #d9d9d9; border-left: 15px solid #c9c9c9; padding: 9px; font-size: 1em; overflow-x: auto;font-family:MonacoConsolasConsolasCourierCouriermonospace;monospace;">
1. 来自代码中
2. 来自外部(GET/POST/DB)
</pre>
<p>	对于代码中的变量(也就是直接量)来说, 变量分配/赋值在编译期, 活跃在执行器, 在请求关闭期被销毁.对于这些变量来说, 使用APC进行Opcode缓存, 则会缓存这部分变量的值. </p>
<p>	而对于来自外部的变量, 变量分配/赋值在编译器后, 执行期前, 在请求关闭期被销毁,对于这些变量来说, 使用APC进行OpCode缓存, 是不会被缓存的.</p>
<p>	今天就着重关注下外部变量的一个部分,GET来的数据的整个生命周期.</p>
<p>	假设, 有如下请求到来:</p>
<pre name="code"  class="sh_sh"  linenum="off"   style="background: #333; color: #d9d9d9; border-left: 15px solid #c9c9c9; padding: 9px; font-size: 1em; overflow-x: auto;font-family:Monacobackground: #333; color: #d9d9d9; border-left: 15px solid #c9c9c9; padding: 9px; font-size: 1em; overflow-x: auto;font-family:MonacoConsolasConsolasCourierCouriermonospace;monospace;">
	GET /index.php?name=laruence&amp;career[]=yahoo&amp;career[]=baidu
</pre>
<p>	而, 在index.php中:</p>
<pre name="code"  class="sh_php"  linenum="off"   style="background: #333; color: #d9d9d9; border-left: 15px solid #c9c9c9; padding: 9px; font-size: 1em; overflow-x: auto;font-family:Monacobackground: #333; color: #d9d9d9; border-left: 15px solid #c9c9c9; padding: 9px; font-size: 1em; overflow-x: auto;font-family:MonacoConsolasConsolasCourierCouriermonospace;monospace;">
&lt;?php
	$name 	= $_GET['name'];
	$career = $_GET['career']; //array
</pre>
<p>	我们知道, 在最后的执行期, $_GET数组必然包含如下片段:</p>
<pre name="code"  class="sh_php"  linenum="off"   style="background: #333; color: #d9d9d9; border-left: 15px solid #c9c9c9; padding: 9px; font-size: 1em; overflow-x: auto;font-family:Monacobackground: #333; color: #d9d9d9; border-left: 15px solid #c9c9c9; padding: 9px; font-size: 1em; overflow-x: auto;font-family:MonacoConsolasConsolasCourierCouriermonospace;monospace;">
	$_GET = array(
		'name'   =&gt; 'laruence',
		'career' =&gt; array(
			'yahoo', 'baidu',
		),
	)
</pre>
<p>	那么, 我们今天就重点关注下, Query String是如何构建成_GET数组的(关于GET变量的生成, 请一并阅读我之前的文章: &#8220;<a href="http://www.laruence.com/2008/11/07/581.html"  target="_blank" >PHP的GET/POST等大变量生成过程</a>&#8220;): </p>
<p>	在请求到来时刻,php_request_startup(定义在main.c)被调用,来做初始化现场. 在这个过程中包括设置超时值,调用各个模块的请求初始化函数. 当然也包括我们关心的, 创建变量环境.</p>
<p>	php_hash_environment根据php.ini中的variables_order来依次初始化各个预定义大变量, 那么对于$_GET来说:</p>
<pre name="code"  class="sh_c"  linenum="off"   style="background: #333; color: #d9d9d9; border-left: 15px solid #c9c9c9; padding: 9px; font-size: 1em; overflow-x: auto;font-family:Monacobackground: #333; color: #d9d9d9; border-left: 15px solid #c9c9c9; padding: 9px; font-size: 1em; overflow-x: auto;font-family:MonacoConsolasConsolasCourierCouriermonospace;monospace;">
...
case 'g':
case 'G':
	if (!_gpc_flags[2]) {
		sapi_module.treat_data(PARSE_GET, NULL, NULL TSRMLS_CC);
		_gpc_flags[2] = 1;
		if (PG(register_globals)) {
			php_autoglobal_merge(&amp;EG(symbol_table),
				Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_GET]) TSRMLS_CC);
		}
	}
break;
...
</pre>
<p>	大体可以看出,这段逻辑,首先通过treat_data来生成变量hash(PG(http_globals)[TRACK_VARS_GET]), 如果打开了auto_register_globals,则再把$_GET数组中的变量加入到符号表中.</p>
<p>	treat_data是属于sapi_module_struct中的一个成员: </p>
<pre name="code"  class="sh_sh"  linenum="off"   style="background: #333; color: #d9d9d9; border-left: 15px solid #c9c9c9; padding: 9px; font-size: 1em; overflow-x: auto;font-family:Monacobackground: #333; color: #d9d9d9; border-left: 15px solid #c9c9c9; padding: 9px; font-size: 1em; overflow-x: auto;font-family:MonacoConsolasConsolasCourierCouriermonospace;monospace;">
 注意:	本文基于apache2handler方式的sapi, 这个启动过程和之前的文章sapi
原理中的启动过程略有不同, php5通过注册apache2的ap_hook_post_config挂钩,
在apache server启动的时候启动php(php_apache_server_startup,定义在
sapi/apache2hander/sapi_apache2.c中), 在这个函数中调用sapi_startup启动sapi,
继而通过调用php_apache2_startup来注册sapi module struct,
然后调用php_module_startup来初始化PHP, 其中又会初始化ZEND引擎,
以及填充zend_module_struct中的treat_data成员(通过php_startup_sapi_content_types)
为php_default_treat_data
</pre>
<p>	现在回过头来继续看treat_data(也就是php_default_treat_data):</p>
<pre name="code"  class="sh_c"  linenum="off"   style="background: #333; color: #d9d9d9; border-left: 15px solid #c9c9c9; padding: 9px; font-size: 1em; overflow-x: auto;font-family:Monacobackground: #333; color: #d9d9d9; border-left: 15px solid #c9c9c9; padding: 9px; font-size: 1em; overflow-x: auto;font-family:MonacoConsolasConsolasCourierCouriermonospace;monospace;">
....
if (arg == PARSE_GET) {     /* GET data */
	c_var = SG(request_info).query_string;
	if (c_var &amp;&amp; *c_var) {
		res = (char *) estrdup(c_var);
		free_buffer = 1;
	} else {
		free_buffer = 0;
	}
} else if (arg == PARSE_COOKIE) {       /* Cookie data */
....
</pre>
<p>	在上面的逻辑中, 给res复制为query_string, SG(request_info)是一个代表了当前请求信息的结构体, 其中query_string是在php_apache_request_ctor中通过复制apache的reqeust_rec结构体中的args而来的. </p>
<p>	对于本文的例子来说, 此时res即为&#8221;name=laruence&#038;career[]=yahoo&#038;career[]=baidu&#8221;, </p>
<p>	继续在treat_data中, 随后的逻辑是:</p>
<pre name="code"  class="sh_c"  linenum="off"   style="background: #333; color: #d9d9d9; border-left: 15px solid #c9c9c9; padding: 9px; font-size: 1em; overflow-x: auto;font-family:Monacobackground: #333; color: #d9d9d9; border-left: 15px solid #c9c9c9; padding: 9px; font-size: 1em; overflow-x: auto;font-family:MonacoConsolasConsolasCourierCouriermonospace;monospace;">
var = php_strtok_r(res, separator, &amp;strtok_buf);
...
while (var) {
	val = strchr(var, '=');

	if (arg == PARSE_COOKIE) {
		/* Remove leading spaces from cookie names,
			needed for multi-cookie header where ; can be followed by a space */
		while (isspace(*var)) {
			var++;
		}
		if (var == val || *var == '\0') {
			goto next_cookie;
		}
	}

	if (val) { /* have a value */
		int val_len;
		unsigned int new_val_len;

		*val++ = '\0';
		php_url_decode(var, strlen(var));
		val_len = php_url_decode(val, strlen(val));
		val = estrndup(val, val_len);
		if (sapi_module.input_filter(arg, var, &amp;val, val_len, &amp;new_val_len TSRMLS_CC)) {
			php_register_variable_safe(var, val, new_val_len, array_ptr TSRMLS_CC);
		}
		efree(val);
	} else {
...
</pre>
<p>	首先, 通过php_strtok_r把res根据&#8221;&#038;&#8221;分割成一个一个的&#8221;key=value&#8221;段, 接下来分别为var和val复制为key和value, 注意到这个过程中会分别对var和val做php_url_decode.</p>
<p>	最后通过php_register_variable_safe, 给array_ptr(此时指向PG(http_globals)[TRACK_VARS_GET], 也就是$_GET)添加一个名为var值为val的成员.</p>
<p>	到了这一步, 我们的$_GET数组中, 就包含了如下的成员:</p>
<pre name="code"  class="sh_php"  linenum="off"   style="background: #333; color: #d9d9d9; border-left: 15px solid #c9c9c9; padding: 9px; font-size: 1em; overflow-x: auto;font-family:Monacobackground: #333; color: #d9d9d9; border-left: 15px solid #c9c9c9; padding: 9px; font-size: 1em; overflow-x: auto;font-family:MonacoConsolasConsolasCourierCouriermonospace;monospace;">
'name'   =&gt; 'laruence',
'career' =&gt; array(
	'yahoo', 'baidu',
),
</pre>
<p>	未完待续(变量的销毁过程)&#8230;<br/>
<script type="text/javascript"  src="http://www.laruence.com/wp-content/plugins/shjs-syntax-hiliter/shjs/lang/sh_sh.js" ></script><script type="text/javascript"  src="http://www.laruence.com/wp-content/plugins/shjs-syntax-hiliter/shjs/lang/sh_sh.js" ></script><script type="text/javascript"  src="http://www.laruence.com/wp-content/plugins/shjs-syntax-hiliter/shjs/lang/sh_php.js" ></script><script type="text/javascript"  src="http://www.laruence.com/wp-content/plugins/shjs-syntax-hiliter/shjs/lang/sh_php.js" ></script><script type="text/javascript"  src="http://www.laruence.com/wp-content/plugins/shjs-syntax-hiliter/shjs/lang/sh_c.js" ></script><script type="text/javascript"  src="http://www.laruence.com/wp-content/plugins/shjs-syntax-hiliter/shjs/lang/sh_sh.js" ></script><script type="text/javascript"  src="http://www.laruence.com/wp-content/plugins/shjs-syntax-hiliter/shjs/lang/sh_c.js" ></script><script type="text/javascript"  src="http://www.laruence.com/wp-content/plugins/shjs-syntax-hiliter/shjs/lang/sh_c.js" ></script><script type="text/javascript"  src="http://www.laruence.com/wp-content/plugins/shjs-syntax-hiliter/shjs/lang/sh_php.js" ></script></p>
<hr/><h2>Comments</h2><ul  style="padding-left:1em;font-size:85%;padding-left:1em;font-size:85%;"><li><a href="http://www.laruence.com/2009/12/26/1198.html" >2009/12/26</a>, Robin writes: Hi，麻烦问问，如果想去掉 "[]"，改成
name=laruence&amp;career=yahoo&amp;career=baidu
$_GET数组还要不变，怎么改？

谢谢了。</li><li><a href="http://www.laruence.com/2009/12/26/1198.html" >2009/12/26</a>, <a href="http://www.laruence.com"  rel="external nofollow"  class="url" >雪候鸟</a> writes: @robin 这样的话,最终career的值为baidu</li><li><a href="http://www.laruence.com/2009/12/26/1198.html" >2009/12/28</a>, <a href="www.phppan.com"  rel="external nofollow"  class="url" >phppan</a> writes: 在window下用vc看也比较舒服
抚琴居主人有一篇文章有相关介绍
http://www.yanbin.org/blog/commentary-on-php-chap1_1-prep.html</li><li><a href="http://www.laruence.com/2009/12/26/1198.html" >2009/12/28</a>, <a href="http://www.metsky.com"  rel="external nofollow"  class="url" >天缘</a> writes: 还没真的没深究过这些源码，佩服博主认真的研究</li><li><a href="http://www.laruence.com/2009/12/26/1198.html" >2009/12/28</a>, phpcoder writes: 强悍的博主, 还有点不明白就是数组是怎么parse来的呢?</li><li><a href="http://www.laruence.com/2009/12/26/1198.html" >2009/12/28</a>, <a href="http://www.laruence.com"  rel="external nofollow"  class="url" >雪候鸟</a> writes: @phpcoder 呵呵,就是简单的字符串parse了, 遇到"[]", 就知道是个数组..</li><li><a href="http://www.laruence.com/2009/12/26/1198.html" >2009/12/30</a>, eve writes: 楼主，求交往</li><li><a href="http://www.laruence.com/2009/12/26/1198.html" >2010/03/25</a>, Anonymous writes: 怎么没有了，写完吧，大虾</li><li><a href="http://www.laruence.com/2009/12/26/1198.html" >2010/06/22</a>, 库从志 writes: 博主 写得很深入</li><li><a href="http://www.laruence.com/2009/12/26/1198.html" >2010/07/25</a>, <a href="http://blog.haohtml.com/index.php/archives/4786"  rel="external nofollow"  class="url" >深入理解PHP原理之变量生命期(一) | haohtml&#39;s blog</a> writes: [...] 本文地址: http://www.laruence.com/2009/12/26/1198.html [...]</li><li><a href="http://www.laruence.com/2009/12/26/1198.html" >2010/08/08</a>, <a href="http://ichenkun.org/blog/2009/11/21/%e7%be%8e%e5%91%b3%e5%88%86%e4%ba%ab1/"  rel="external nofollow"  class="url" >美味分享1 | ichenkun</a> writes: [...] 5: 深入理解PHP原理之变量 生命期(一) [...]</li><li><a href="http://www.laruence.com/2009/12/26/1198.html" >2010/09/18</a>, <a href="http://chenkun.me/blog/2009/11/21/delicious-1/"  rel="external nofollow"  class="url" >美味分享1 | chenkun</a> writes: [...] 5: 深入理解PHP原理之变量 生命期(一) [...]</li><li><a href="http://www.laruence.com/2009/12/26/1198.html" >2011/03/20</a>, <a href="http://www.w3hacker.com/?p=198"  rel="external nofollow"  class="url" >深入理解PHP原理之变量生命期(一) | 万维网黑客联盟</a> writes: [...] 本文地址: http://www.laruence.com/2009/12/26/1198.html [...]</li></ul><hr/><h2>Related posts:</h2><ul  style="padding-left:1em;font-size:85%;padding-left:1em;font-size:85%;"><li><a href="http://www.laruence.com/2009/07/27/1020.html"  rel="bookmark"  title="Permanent Link: 深入理解PHP原理之错误抑制与内嵌HTML" >深入理解PHP原理之错误抑制与内嵌HTML</a></li><li><a href="http://www.laruence.com/2008/08/26/463.html"  rel="bookmark"  title="Permanent Link: 深入理解PHP原理之变量作用域(Scope in PHP)" >深入理解PHP原理之变量作用域(Scope in PHP)</a></li><li><a href="http://www.laruence.com/2011/03/29/1949.html"  rel="bookmark"  title="Permanent Link: 深入理解PHP原理之Session Gc的一个小概率Notice" >深入理解PHP原理之Session Gc的一个小概率Notice</a></li><li><a href="http://www.laruence.com/2010/06/20/1602.html"  rel="bookmark"  title="Permanent Link: 深入理解PHP之匿名函数" >深入理解PHP之匿名函数</a></li><li><a href="http://www.laruence.com/2010/05/04/1450.html"  rel="bookmark"  title="Permanent Link: 深入理解PHP之require/include顺序" >深入理解PHP之require/include顺序</a></li></ul><hr/><small  style="font-size:85%;font-size:85%;">Copyright &copy; 2010 <a href="http://www.laruence.com"  target="_blank" >风雪之隅</a> 版权所有, 转载务必注明. 该Feed只供个人使用, 禁止未注明的转载或商业应用. 非法应用的, 一切法律后果自负. 如有问题, 可发E-mail至my at laruence.com.(Digital Fingerprint: 73540ba0a1738d7d07d4b6038d5615e2)</small><h2 class="related_post_title" >Related Posts:</h2><ul class="related_post"   style="padding-left:1em;font-size:85%;padding-left:1em;font-size:85%;"><li><a href="http://www.laruence.com/2009/10/15/1131.html"  title="提升PHP性能之改变Zend引擎分发方式" >提升PHP性能之改变Zend引擎分发方式</a></li><li><a href="http://www.laruence.com/2008/11/07/581.html"  title="PHP的GET/POST等大变量生成过程" >PHP的GET/POST等大变量生成过程</a></li><li><a href="http://www.laruence.com/2008/09/23/539.html"  title="使用PHP Embed SAPI实现Opcodes查看器" >使用PHP Embed SAPI实现Opcodes查看器</a></li><li><a href="http://www.laruence.com/2008/08/24/377.html"  title="PHP源码分析之Global关键字" >PHP源码分析之Global关键字</a></li><li><a href="http://www.laruence.com/2008/08/22/412.html"  title="深入理解PHP原理之变量(Variables inside PHP)" >深入理解PHP原理之变量(Variables inside PHP)</a></li><li><a href="http://www.laruence.com/2008/08/12/180.html"  title="深入理解Zend SAPIs(Zend SAPI Internals)" >深入理解Zend SAPIs(Zend SAPI Internals)</a></li><li><a href="http://www.laruence.com/2008/04/04/17.html"  title="在PHP Module中获取$_GET/$_POST/$_COOKIE的方法研究" >在PHP Module中获取$_GET/$_POST/$_COOKIE的方法研究</a></li><li><a href="http://www.laruence.com/2012/02/08/2528.html"  title="PHP-5.3.9远程执行任意代码漏洞(CVE-2012-0830)" >PHP-5.3.9远程执行任意代码漏洞(CVE-2012-0830)</a></li><li><a href="http://www.laruence.com/2012/02/02/2515.html"  title="我们什么时候应该使用异常?" >我们什么时候应该使用异常?</a></li><li><a href="http://www.laruence.com/2012/02/01/2503.html"  title="使用exit(-1)为什么得到255退出码?" >使用exit(-1)为什么得到255退出码?</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.laruence.com/2009/12/26/1198.html/feed</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>深入理解PHP原理之变量(Variables inside PHP)</title>
		<link>http://www.laruence.com/2008/08/22/412.html</link>
		<comments>http://www.laruence.com/2008/08/22/412.html#comments</comments>
		<pubDate>Fri, 22 Aug 2008 14:36:18 +0000</pubDate>
		<dc:creator>雪候鸟</dc:creator>
				<category><![CDATA[PHP应用]]></category>
		<category><![CDATA[PHP源码分析]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[variable]]></category>
		<category><![CDATA[Zend/PHP]]></category>
		<category><![CDATA[zval]]></category>

		<guid isPermaLink="false">http://www.laruence.com/?p=412</guid>
		<description><![CDATA[<p>或许你知道，或许你不知道，PHP是一个弱类型，动态的脚本语言。所谓弱类型，就是说PHP并不严格验证变量类型(严格来讲，PHP是一个中强类型语言,这部分内容会在以后的文章中叙述)，在申明一个变量的时候，并不需要显示指明它保存的数据的类型。而PHP的核心ZE是用C编写的，大家都知道C是一个强类型语言，也就是说，在C中所有的变量在它被声明到最终销毁，都只能保存一种类型的数据。 那么PHP是如何在ZE的基础上实现弱类型的呢？且听我慢慢道来....</p>]]></description>
			<content:encoded><![CDATA[<div class="copyright" >
<ul  style="padding-left:1em;font-size:85%;padding-left:1em;font-size:85%;">
<li>作者: <a href="http://www.laruence.com" >Laruence</a>(<a href="http://www.twitter.com/laruence"  target="meme"  title="Twitter" ><img src="/images/ico-twitter.png" /></a> <a href="http://t.sina.com/laruence"  target="meme"  title="新浪微博" ><img src="/images/ico-sina.png" /></a> <a href="http://fusion.google.com/add?feedurl=http://www.laruence.com/feed"  target="meme"  title="Google阅读器" ><img src="/images/ico-google.png" /></a> <a href="mailto:laruence@yahoo.com.cn"  target="meme"  title="邮件" ><img src="/images/ico-mail.png" /></a>)</li>
<li>本文地址: <a href="http://www.laruence.com/2008/08/22/412.html"  title="Permanet Link to 深入理解PHP原理之变量(Variables inside PHP)" >http://www.laruence.com/2008/08/22/412.html</a></li>
</li>
<li>转载请注明出处 </li>
</ul></div>
<p>或许你知道，或许你不知道，PHP是一个弱类型，动态的脚本语言。所谓弱类型，就是说PHP并不严格验证变量类型(严格来讲，PHP是一个中强类型语言,这部分内容会在以后的文章中叙述)，在申明一个变量的时候，并不需要显示指明它保存的数据的类型：</p>
<pre name="code"  class="sh_php"  linenum="off"   style="background: #333; color: #d9d9d9; border-left: 15px solid #c9c9c9; padding: 9px; font-size: 1em; overflow-x: auto;font-family:Monacobackground: #333; color: #d9d9d9; border-left: 15px solid #c9c9c9; padding: 9px; font-size: 1em; overflow-x: auto;font-family:MonacoConsolasConsolasCourierCouriermonospace;monospace;">
&lt;?php
  $var = 1; //int
  $var = &quot;laruence&quot;; //string
  $var = 1.0002; //float
  $var = array(); // array
  $var = new Exception('error'); //object;
</pre>
<p>  动态语言，就是说，PHP的语言结构在运行期是可以改变的，比如我们在运行期require一个函数定义文件，从而导致语言的函数表动态的改变。<br/>
  所谓脚本语言，就是说，PHP并不是独立运行的，要运行PHP我们需要PHP解析器：</p>
<pre name="code"  class="sh_shell"  linenum="off"   style="background: #333; color: #d9d9d9; border-left: 15px solid #c9c9c9; padding: 9px; font-size: 1em; overflow-x: auto;font-family:Monacobackground: #333; color: #d9d9d9; border-left: 15px solid #c9c9c9; padding: 9px; font-size: 1em; overflow-x: auto;font-family:MonacoConsolasConsolasCourierCouriermonospace;monospace;">
  /usr/bin/php -f example.php
</pre>
<p>   我前面的文章中已经讲过，PHP的执行是通过Zend engine(ZE, Zend引擎), ZE是用C编写的，大家都知道C是一个强类型语言，也就是说，在C中所有的变量在它被声明到最终销毁，都只能保存一种类型的数据。 那么PHP是如何在ZE的基础上实现弱类型的呢？</p>
<div style="color:blue;padding-lef" >首先要声明一点，如果你以前没有接触过PHP的源码分析，扩展开发。 如果你并不了解PHP的架构， 没有听说ZE，那么我建议你先看看我前面的文章,尤其推荐：</p>
<li><a href="http://www.laruence.com/2008/08/11/147.html" >深入浅出PHP(PHP Internals)</a></li>
<li><a href="http://www.laruence.com/2008/06/18/221.html" >深入理解PHP原理之Opcodes</a></li>
</div>
<p>   在PHP中，所有的变量都是用一个结构-zval来保存的， 在Zend/zend.h中我们可以看到zval的定义：</p>
<pre name="code"  class="sh_cpp"  linenum="off"   style="background: #333; color: #d9d9d9; border-left: 15px solid #c9c9c9; padding: 9px; font-size: 1em; overflow-x: auto;font-family:Monacobackground: #333; color: #d9d9d9; border-left: 15px solid #c9c9c9; padding: 9px; font-size: 1em; overflow-x: auto;font-family:MonacoConsolasConsolasCourierCouriermonospace;monospace;">
  typedef struct _zval_struct {
    zvalue_value value;
    zend_uint refcount;
    zend_uchar type;
    zend_uchar is_ref;
  } zval;
 </pre>
<p>    其中zvalue_value是真正保存数据的关键部分，现在到了揭晓谜底的时候了，PHP是如何在ZE的基础上实现弱类型的呢？ 因为zvalue_value是个联合体(union), </p>
<pre name="code"  class="sh_cpp"  linenum="off"   style="background: #333; color: #d9d9d9; border-left: 15px solid #c9c9c9; padding: 9px; font-size: 1em; overflow-x: auto;font-family:Monacobackground: #333; color: #d9d9d9; border-left: 15px solid #c9c9c9; padding: 9px; font-size: 1em; overflow-x: auto;font-family:MonacoConsolasConsolasCourierCouriermonospace;monospace;">
typedef union _zvalue_value {
    long lval;
    double dval;
    struct {
        char *val;
        int len;
    } str;
    HashTable *ht;
    zend_object_value obj;
} zvalue_value;
</pre>
<p>   那么这个结构是如何储存PHP中的多种类型的呢？<br/>
   PHP中常见的变量类型有：</p>
<pre name="code"  class="sh_shell"  linenum="off"   style="background: #333; color: #d9d9d9; border-left: 15px solid #c9c9c9; padding: 9px; font-size: 1em; overflow-x: auto;font-family:Monacobackground: #333; color: #d9d9d9; border-left: 15px solid #c9c9c9; padding: 9px; font-size: 1em; overflow-x: auto;font-family:MonacoConsolasConsolasCourierCouriermonospace;monospace;">
1. 整型/浮点/长整型/bool值 等等
2. 字符串
3. 数组/关联数组
4. 对象
5. 资源
  </pre>
<p>   PHP根据zval中的type字段来储存一个变量的真正类型，然后根据type来选择如何获取zvalue_value的值，比如对于整型和bool值:</p>
<pre name="code"  class="sh_shell"  linenum="off"   style="background: #333; color: #d9d9d9; border-left: 15px solid #c9c9c9; padding: 9px; font-size: 1em; overflow-x: auto;font-family:Monacobackground: #333; color: #d9d9d9; border-left: 15px solid #c9c9c9; padding: 9px; font-size: 1em; overflow-x: auto;font-family:MonacoConsolasConsolasCourierCouriermonospace;monospace;">
   zval.type = IS_LONG;//整形
   zval.type = IS_BOOL;//布尔值
</pre>
<p>   就去取zval.value.lval,对于bool值来说lval∈(0|1);<br/>
   如果是双精度，或者float则会去取zval.value的dval。<br/>
   而如果是字符串，那么:</p>
<pre name="code"  class="sh_shell"  linenum="off"   style="background: #333; color: #d9d9d9; border-left: 15px solid #c9c9c9; padding: 9px; font-size: 1em; overflow-x: auto;font-family:Monacobackground: #333; color: #d9d9d9; border-left: 15px solid #c9c9c9; padding: 9px; font-size: 1em; overflow-x: auto;font-family:MonacoConsolasConsolasCourierCouriermonospace;monospace;">
   zval.type = IS_STRING
</pre>
<p>   这个时候，就会取:<br/>
    zval.value.str<br/>
   而这个也是个结构，存有C分格的字符串和字符串的长度。</p>
<p>   而对于数组和对象，则type分别对应IS_ARRAY, IS_OBJECT, 相对应的则分别取zval.value.ht和obj</p>
<p>   比较特别的是资源，在PHP中，资源是个很特别的变量，任何不属于PHP内建的变量类型的变量，都会被看作成资源来进行保存，比如，数据库句柄，打开的文件句柄等等。 对于资源:</p>
<pre name="code"  class="sh_php"  linenum="off"   style="background: #333; color: #d9d9d9; border-left: 15px solid #c9c9c9; padding: 9px; font-size: 1em; overflow-x: auto;font-family:Monacobackground: #333; color: #d9d9d9; border-left: 15px solid #c9c9c9; padding: 9px; font-size: 1em; overflow-x: auto;font-family:MonacoConsolasConsolasCourierCouriermonospace;monospace;">
   type = IS_RESOURCE
</pre>
<p>   这个时候，会去取zval.value.lval， 此时的lval是个整型的指示器， 然后PHP会再根据这个指示器在PHP内建的一个资源列表中查询相对应的资源(这部分的内容，我以后会单独开一个篇文章来介绍)，目前，你只要知道此时的lval就好像是对应于资源链表的偏移值。</p>
<pre name="code"  class="sh_php"  linenum="off"   style="background: #333; color: #d9d9d9; border-left: 15px solid #c9c9c9; padding: 9px; font-size: 1em; overflow-x: auto;font-family:Monacobackground: #333; color: #d9d9d9; border-left: 15px solid #c9c9c9; padding: 9px; font-size: 1em; overflow-x: auto;font-family:MonacoConsolasConsolasCourierCouriermonospace;monospace;">
 ZEND_FETCH_RESOURCE(con, type, zval *, default, resource_name, resource_type);
</pre>
<p>    借用这样的机制，PHP就实现了弱类型，因为对于ZE的来说，它所面对的永远都是同一种类型，那就是zval。<br/>
    ps:明天team出去building，我想着应该在走之前写点东西给我的blog reader来消磨周末。今天就简单先开个头，下一次，我将进一步介绍PHP的变量，作用域，以及变量的copy on write和change on write机制， 待续&#8230;.<br/>
  <script type="text/javascript"  src="http://www.laruence.com/wp-content/plugins/shjs-syntax-hiliter/shjs/lang/sh_php.js" ></script><script type="text/javascript"  src="http://www.laruence.com/wp-content/plugins/shjs-syntax-hiliter/shjs/lang/sh_shell.js" ></script><script type="text/javascript"  src="http://www.laruence.com/wp-content/plugins/shjs-syntax-hiliter/shjs/lang/sh_cpp.js" ></script><script type="text/javascript"  src="http://www.laruence.com/wp-content/plugins/shjs-syntax-hiliter/shjs/lang/sh_cpp.js" ></script><script type="text/javascript"  src="http://www.laruence.com/wp-content/plugins/shjs-syntax-hiliter/shjs/lang/sh_shell.js" ></script><script type="text/javascript"  src="http://www.laruence.com/wp-content/plugins/shjs-syntax-hiliter/shjs/lang/sh_shell.js" ></script><script type="text/javascript"  src="http://www.laruence.com/wp-content/plugins/shjs-syntax-hiliter/shjs/lang/sh_shell.js" ></script><script type="text/javascript"  src="http://www.laruence.com/wp-content/plugins/shjs-syntax-hiliter/shjs/lang/sh_php.js" ></script><script type="text/javascript"  src="http://www.laruence.com/wp-content/plugins/shjs-syntax-hiliter/shjs/lang/sh_php.js" ></script></p>
<hr/><h2>Comments</h2><ul  style="padding-left:1em;font-size:85%;padding-left:1em;font-size:85%;"><li><a href="http://www.laruence.com/2008/08/22/412.html" >2008/08/23</a>, 左手 writes: 太佩服你了，强大的很</li><li><a href="http://www.laruence.com/2008/08/22/412.html" >2008/08/26</a>, <a href="http://fy"  rel="external nofollow"  class="url" >fj</a> writes: mark</li><li><a href="http://www.laruence.com/2008/08/22/412.html" >2008/08/27</a>, bush writes: 在PHP中，所有的变量都是用一个结构-zval来保存的， 在Zend/zend.h中我们可以看到zval的定义：

在php应用中 Zend相关的文件没有找到或见过  它属于哪一部分呢</li><li><a href="http://www.laruence.com/2008/08/22/412.html" >2008/08/27</a>, <a href="http://www.laruence.com"  rel="external nofollow"  class="url" >雪候鸟</a> writes: 我指的Zend/zend.h是相当于PHP源码结构树的根目录
比如,我看的是PHP5.2,那么Zend就是
PHP5.2-SRC/Zend/</li><li><a href="http://www.laruence.com/2008/08/22/412.html" >2008/09/23</a>, 狂笨地太阳 writes: 太好了，终于理解PHP的变量是怎么个样子了。。PHP变量类型不同，ZVAL的TYPE就不同。</li><li><a href="http://www.laruence.com/2008/08/22/412.html" >2008/11/25</a>, <a href="http://www.benleo.cn/?p=186"  rel="external nofollow"  class="url" >完全COPY : 深入理解PHP原理之变量分离/引用(Variables Separation)</a> writes: [...] Separation) 在前面的文章中我已经介绍了PHP的变量的内部表示(深入理解PHP原理之变量(Variables inside PHP))，以及PHP中作用域的实现机制(深入理解PHP原理之变量作用域(Scope inside [...]</li><li><a href="http://www.laruence.com/2008/08/22/412.html" >2008/11/26</a>, yzcj007 writes: 感谢搂主，写得很棒，加油写，等着看呢！</li><li><a href="http://www.laruence.com/2008/08/22/412.html" >2010/03/25</a>, Anonymous writes: 牛人</li><li><a href="http://www.laruence.com/2008/08/22/412.html" >2010/05/18</a>, <a href="http://www.laruence.com/2010/05/18/1482.html"  rel="external nofollow"  class="url" >深入理解PHP原理之对象(一) | 风雪之隅</a> writes: [...] 对象的结构 在PHP5中, 一个对象, 还是以一个zval做为载体的, 还记得什么是Zval么(深入理解PHP原理之变量). [...]</li><li><a href="http://www.laruence.com/2008/08/22/412.html" >2010/05/26</a>, <a href="http://crazyphper.com/wblog/archives/777"  rel="external nofollow"  class="url" >深入理解 PHP之require/include顺序 &laquo; 大熊猫 &#8211; konakona ——PHP程序员</a> writes: [...] 在PHP5中, 一个对象, 还是以一个zval做为载体的, 还记得什么是Zval么(深入理解 PHP原理之变量). [...]</li><li><a href="http://www.laruence.com/2008/08/22/412.html" >2010/07/30</a>, <a href="http://zhidao.123doing.com/32792.html"  rel="external nofollow"  class="url" >关于引用的一个小问题。。。散分。。 - PHP常见问题 - 关于引用 一个小问题 散分 PHP 基础编程 - 123Doing</a> writes: [...] unset只是将$t指向的zval结构体的refcount &#8211; 1,然后清除符号表里的&#8217;t&#39;,去除$t与zval的关联但是$s仍然是关联zval的。我说不明白，有一篇高手写的文章专门讲这个的，在本坛我贴出来不少次了，你认真看看。http://www.laruence.com/2008/08/22/412.html [...]</li><li><a href="http://www.laruence.com/2008/08/22/412.html" >2010/09/19</a>, <a href="http://www.yakecan.com/archives/460"  rel="external nofollow"  class="url" >(转)深入理解PHP原理之变量分离/引用(Variables Separation) &raquo; Creative Power</a> writes: [...] 在前面的文章中我已经介绍了PHP的变量的内部表示(深入理解PHP原理之变量(Variables inside PHP))，以及PHP中作用域的实现机制(深入理解PHP原理之变量作用域(Scope inside PHP))。这节我们就接着前面的文章，继续介绍PHP中变量分离和引用的概念： [...]</li><li><a href="http://www.laruence.com/2008/08/22/412.html" >2011/01/31</a>, <a href="http://zhidao.123doing.com/52141.html"  rel="external nofollow"  class="url" >关于引用的一个小问题。。。散分。。 - PHP常见问题 - [标签:tags] - 开源网 | 123Doing</a> writes: [...] 如果你在php4和php5中分别执行上述代码，则php4 得到 21php5 得到 22  unset只是将$t指向的zval结构体的refcount &#8211; 1,然后清除符号表里的&#8217;t&#039;,去除$t与zval的关联但是$s仍然是关联zval的。我说不明白，有一篇高手写的文章专门讲这个的，在本坛我贴出来不少次了，你认真看看。http://www.laruence.com/2008/08/22/412.html 关键是这篇http://www.laruence.com/2008/09/19/520.html然后再结合php的GC原理会更深入一些。http://www.php.net/manual/en/features.gc.refcounting-basics.php [...]</li><li><a href="http://www.laruence.com/2008/08/22/412.html" >2011/03/18</a>, <a href="http://51nosql.com"  rel="external nofollow"  class="url" >51nosql</a> writes: 向大牛学习，关注</li><li><a href="http://www.laruence.com/2008/08/22/412.html" >2011/03/20</a>, <a href="http://www.iirr.info/blog/?p=155"  rel="external nofollow"  class="url" >HorseLuke@微碌 &raquo; Blog Archive &raquo; php缓存扩展频繁存储/读取数组引发CPU过高问题排查手记（php-memcache为例）</a> writes: [...] [2]laruence. 深入理解PHP原理之变量(Variables inside PHP)：http://www.laruence.com/2008/08/22/412.html [...]</li><li><a href="http://www.laruence.com/2008/08/22/412.html" >2011/03/23</a>, liano writes: 牛人啊，我现在在学php能否给我个联系地址请教你一下啊？
qq：584418561</li><li><a href="http://www.laruence.com/2008/08/22/412.html" >2011/08/23</a>, Forever writes: 照这样说每个变量占用的内存都比较大，因为它是结构体类型啊。结构体占用的内存不是所有类型加起来的嘛</li><li><a href="http://www.laruence.com/2008/08/22/412.html" >2011/08/23</a>, <a href="http://www.laruence.com"  rel="external nofollow"  class="url" >雪候鸟</a> writes: @Forever 不是结构体, 是union ;)</li><li><a href="http://www.laruence.com/2008/08/22/412.html" >2011/09/02</a>, <a href="http://warpigallen.sinaapp.com/?p=13"  rel="external nofollow"  class="url" >深入理解PHP原理之变量(Variables inside PHP) | warpig_allen&#039;s blog</a> writes: [...] 本文地址: http://www.laruence.com/2008/08/22/412.html [...]</li></ul><hr/><h2>Related posts:</h2><ul  style="padding-left:1em;font-size:85%;padding-left:1em;font-size:85%;"><li><a href="http://www.laruence.com/2008/08/26/463.html"  rel="bookmark"  title="Permanent Link: 深入理解PHP原理之变量作用域(Scope in PHP)" >深入理解PHP原理之变量作用域(Scope in PHP)</a></li><li><a href="http://www.laruence.com/2008/09/19/520.html"  rel="bookmark"  title="Permanent Link: 深入理解PHP原理之变量分离/引用(Variables Separation)" >深入理解PHP原理之变量分离/引用(Variables Separation)</a></li><li><a href="http://www.laruence.com/2009/06/01/905.html"  rel="bookmark"  title="Permanent Link: 开心网偷菜外挂" >开心网偷菜外挂</a></li><li><a href="http://www.laruence.com/2009/07/27/1020.html"  rel="bookmark"  title="Permanent Link: 深入理解PHP原理之错误抑制与内嵌HTML" >深入理解PHP原理之错误抑制与内嵌HTML</a></li><li><a href="http://www.laruence.com/2011/03/29/1949.html"  rel="bookmark"  title="Permanent Link: 深入理解PHP原理之Session Gc的一个小概率Notice" >深入理解PHP原理之Session Gc的一个小概率Notice</a></li></ul><hr/><small  style="font-size:85%;font-size:85%;">Copyright &copy; 2010 <a href="http://www.laruence.com"  target="_blank" >风雪之隅</a> 版权所有, 转载务必注明. 该Feed只供个人使用, 禁止未注明的转载或商业应用. 非法应用的, 一切法律后果自负. 如有问题, 可发E-mail至my at laruence.com.(Digital Fingerprint: 73540ba0a1738d7d07d4b6038d5615e2)</small><h2 class="related_post_title" >Related Posts:</h2><ul class="related_post"   style="padding-left:1em;font-size:85%;padding-left:1em;font-size:85%;"><li><a href="http://www.laruence.com/2009/12/26/1198.html"  title="深入理解PHP原理之变量生命期(一)" >深入理解PHP原理之变量生命期(一)</a></li><li><a href="http://www.laruence.com/2008/09/23/539.html"  title="使用PHP Embed SAPI实现Opcodes查看器" >使用PHP Embed SAPI实现Opcodes查看器</a></li><li><a href="http://www.laruence.com/2008/09/19/520.html"  title="深入理解PHP原理之变量分离/引用(Variables Separation)" >深入理解PHP原理之变量分离/引用(Variables Separation)</a></li><li><a href="http://www.laruence.com/2008/08/26/463.html"  title="深入理解PHP原理之变量作用域(Scope in PHP)" >深入理解PHP原理之变量作用域(Scope in PHP)</a></li><li><a href="http://www.laruence.com/2008/08/15/274.html"  title="PHP 源代码分析 V0.0.2" >PHP 源代码分析 V0.0.2</a></li><li><a href="http://www.laruence.com/2008/08/14/250.html"  title="实现PHP的编译执行分离(separating compilation and execution)" >实现PHP的编译执行分离(separating compilation and execution)</a></li><li><a href="http://www.laruence.com/2008/08/12/180.html"  title="深入理解Zend SAPIs(Zend SAPI Internals)" >深入理解Zend SAPIs(Zend SAPI Internals)</a></li><li><a href="http://www.laruence.com/2008/08/12/164.html"  title="深入理解PHP原理之函数(Introspecting PHP Function)" >深入理解PHP原理之函数(Introspecting PHP Function)</a></li><li><a href="http://www.laruence.com/2008/08/11/147.html"  title="深入浅出PHP(Exploring PHP)" >深入浅出PHP(Exploring PHP)</a></li><li><a href="http://www.laruence.com/2008/06/18/221.html"  title="深入理解PHP原理之Opcodes" >深入理解PHP原理之Opcodes</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.laruence.com/2008/08/22/412.html/feed</wfw:commentRss>
		<slash:comments>19</slash:comments>
		</item>
	</channel>
</rss>

