<?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>zephir &#8211; 有意与无意之间</title>
	<atom:link href="https://zhangxihai.cn/archives/tag/zephir/feed" rel="self" type="application/rss+xml" />
	<link>https://zhangxihai.cn</link>
	<description>千淘万漉虽辛苦 吹尽狂沙始到金 - 生命不息 编程不止</description>
	<lastBuildDate>Mon, 02 Nov 2020 04:05:55 +0000</lastBuildDate>
	<language>zh-CN</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.0.11</generator>
	<item>
		<title>zephir中引用赋值和参数的传引用实现</title>
		<link>https://zhangxihai.cn/archives/50</link>
					<comments>https://zhangxihai.cn/archives/50#respond</comments>
		
		<dc:creator><![CDATA[胖爷]]></dc:creator>
		<pubDate>Thu, 29 Oct 2020 14:36:33 +0000</pubDate>
				<category><![CDATA[编码]]></category>
		<category><![CDATA[zephir]]></category>
		<guid isPermaLink="false">http://zhangxihai.cn/?p=50</guid>

					<description><![CDATA[近期在修改一些Phalcon的底层实现时，发现zephir并未提供引用赋值和参数的传引用特性，导致某些特定场景的代码无法实施，例如循环调用中要求不能抛出异常，只能用一个最外层的handle来存储循环中异常或错误，这就要求必须使用参数的传引用特性，所以只能通过一些变通方法来变通实现。 引用赋值 使用&#38;进行引用赋值，编译时会引发异常并提醒你官方并不支持引...]]></description>
										<content:encoded><![CDATA[<p>近期在修改一些Phalcon的底层实现时，发现zephir并未提供引用赋值和参数的传引用特性，导致某些特定场景的代码无法实施，例如循环调用中要求不能抛出异常，只能用一个最外层的handle来存储循环中异常或错误，这就要求必须使用参数的传引用特性，所以只能通过一些变通方法来变通实现。</p>
<h3>引用赋值</h3>
<p>使用&amp;进行引用赋值，编译时会引发异常并提醒你官方并不支持引用赋值，但是可以通过Optimizer扩展来实现引用赋值。</p>
<p>ext/zep_ref.h ：</p>
<pre><code class="language-c">#ifndef ZEP_REF_H
#define ZEP_REF_H

#include &lt;Zend/zend.h&gt;
#include &lt;Zend/zend_API.h&gt;

void ZEP_REF(zval* dst, zval* src);

#endif</code></pre>
<p>ext/zep_ref.c :</p>
<pre><code class="language-c">#ifdef HAVE_CONFIG_H
#include &quot;config.h&quot;
#endif

#include &lt;php.h&gt;
#include &quot;php_ext.h&quot;
#include &quot;ext.h&quot;

#include &quot;kernel/main.h&quot;
#include &quot;kernel/exit.h&quot;
#include &lt;Zend/zend.h&gt;
#include &lt;Zend/zend_API.h&gt;
#include &quot;zep_ref.h&quot;

void ZEP_REF(zval* dst, zval* src)
{
   int refcount = Z_REFCOUNT_P(dst);
   zval_dtor(&amp;dst);
   ZVAL_NEW_REF(dst, src);
   Z_SET_REFCOUNT_P(dst, refcount);
}</code></pre>
<p>ext/opmitizers/ZepRefOptimizer.php</p>
<pre><code class="language-php">&lt;?php
namespace Zephir\Optimizers\FunctionCall;

use Zephir\Call;
use Zephir\CompilationContext;
use Zephir\CompiledExpression;
use Zephir\CompilerException;
use Zephir\Optimizers\OptimizerAbstract;

class ZepRefOptimizer extends OptimizerAbstract
{
    public function optimize(array $expression, Call $call, CompilationContext $context)
    {
        $context-&gt;headersManager-&gt;add(&#039;zep_ref&#039;);
        if (count($expression[&#039;parameters&#039;]) != 2) {
            throw new CompilerException(&quot;&#039;zep_ref&#039; requires two parameter&quot;, $expression);
        }

        $resolvedParams = $call-&gt;getReadOnlyResolvedParams($expression[&#039;parameters&#039;], $context, $expression);

        $context-&gt;codePrinter-&gt;output(
            sprintf(&#039;ZEP_REF(%s, %s);&#039;, $resolvedParams[0], $resolvedParams[1])
        );

        return new CompiledExpression(&#039;null&#039;, null, $expression);
    }
}</code></pre>
<p>在config.json里添加:</p>
<pre><code class="language-script">&quot;optimizer-dirs&quot;: [
    &quot;ext/optimizers&quot;
],
&quot;extra-sources&quot;: [
    &quot;zep_ref.c&quot;
],</code></pre>
<p>使用很简单</p>
<pre><code class="language-php">var a = &quot;采蘑菇的小姑娘&quot;;
var b;
zep_ref(a, b);
let a = &quot;爱吃鱼的大脸猫&quot;;
echo b;</code></pre>
<p>输出的是: 爱吃鱼的大脸猫</p>
<h3>参数的传引用</h3>
<p>方法传参使用&amp;并不会引发异常，但是也不会达到预期的结果，在php底层，标记参数是否是按值传递，还是按应用传递仅仅是一个标记值的0与1的区别，但事实上在zephir中这个问题要复杂的多，比如考虑匿名函数，考虑use()，所以无法从扩展层面解决，除非你有能力修改编译器代码。所以只能通过一些其它的方法来模拟实现参数的传引用。</p>
<p>将需要传引用的参数作为返回值返回通常是一种可以解决大多数需要的办法，但是并不是所有场景都可以这么做，例如匿名函数作为方法参数且多层循环调用或者某一层无法返回值得时候，就必须考虑使用参数传引用。</p>
<p>一个方法是利用超全局变量进行读写，但是要注意健名可能存在的重复：</p>
<pre><code class="language-php">var key = uuid();
var str = &quot;采蘑菇的小姑娘&quot;;
let _ENV[key] = str;

var callback = function () use (key) {
    let _ENV[key] = &quot;爱吃鱼的大脸猫&quot;;
}

call_user_func(callback, []);
let str = _ENV[key];
echo str;</code></pre>
<p>另一种方法是利用对象进行传递，zephir和php一样也是将对象指针传递到方法内，所以只需要修改对象的属性值，就可以在方法之外将其取出来 Ref.zep ：</p>
<pre><code class="language-php">namespace Anas\Support;

class Ref
{
    private values = [];

    public function __contract(array values = [])
    {
        if ! empty(values) {
            let this-&gt;values = values;
        }
    }

    public function set(string name, value)
    {
        let this-&gt;values[name] = value;
    }

    public function get(string name)
    {
        var value;
        let value = isset(this-&gt;values[name]) ? this-&gt;values[name] : null;

        return value;
    }
}
</code></pre>
<p>使用：</p>
<pre><code class="language-php">var key = &quot;hello&quot;;
var str = &quot;采蘑菇的小姑娘&quot;;
var ref;
let ref = new Ref();
ref-&gt;set(key, str);

var callback = function () use (key) {
    ref-&gt;set(key, &quot;爱吃鱼的大脸猫&quot;);
}

call_user_func(callback, []);
let str = ref-&gt;get(key);
echo str;</code></pre>
<p>这些方法都是变通实现，和真正的传引用在性能上还有有差异，不是万不得已还是别用。</p>
<p>End!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zhangxihai.cn/archives/50/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
