PHP中的引用

php中文网
发布: 2016-06-23 14:32:29
原创
1242人浏览过

Welcome back! In my last column I introduced you to basic PHP references and how they are used. This week, I'll take that basic introduction a step further and implement some of the more advanced uses for references in PHP. First, I'll be discussing the concept of returning a reference from a function, followed by using references within objects. Let's get started. Returning by Reference

last week, i discussed how references could be used as parameters of functions in order to return multiple values. this week, i'll look at ways to use references as the actual return value of the function and how this can be useful to developers. to assist us in our discussion, consider the following classes:

<?php    class A {        function printmsg() {            echo  "Class is A<br>";        }    }    class B {        function printmsg() {            echo "Class is B<br>";        }    }$toolbox[] = new A();$toolbox[] = new B();?>
登录后复制

As you can see, we have created two very simple classes, A and B, each of which contains a single member function called printmsg(). Then, an instance of each class is created and stored in the array $toolbox. With this overhead out of the way, let's discuss the passing by reference function. Although there are many uses for a return by reference function, the specific function that I will be creating today will accept a single parameter (for a simple case like this, a boolean value) and return a reference to one of the above created objects, as shown.

<?php    function &selectObject($which = false) {        global $toolbox;        if($which == true)             return $toolbox[0];        return $toolbox[1];    }    $tool =& selectObject(true);    $tool->printmsg();    $anothertool =& selectObject(false);    $anothertool->printmsg();?>
登录后复制

So what exactly does this selectObject() function we've created do? Looking at the function declaration, we see that it takes a single boolean parameter $which, but what is the ampersand (&) character in front of the function name for? This symbol defines our function as one that returns a PHP reference instead of a complete variable. Looking at the code within the function, we can see that the function returns one of the objects stored in the $toolbox array defined previously. Hence, depending on the value of our parameter, we return a reference to one of the objects we've defined.

Related Reading

PHP Cookbook
By David Sklar, Adam Trachtenberg

立即学习PHP免费学习笔记(深入)”;

Table of Contents
Index
Sample Chapter

Read Online--Safari Search this book on Safari:  
Only This Book All of Safari
Code Fragments only

Let's take a look at how the function is actually used. As you can see above, we have initialized the variable $tool to the value that selectObject() returns. Note that we are not using the standard syntax for a variable assignment, but rather the reference-binding syntax introduced in my last column. Since selectObject() is a reference-returning function, we must treat $tool as a reference variable and assign it using the appropriate "=&" syntax. Once properly assigned, $tool now points to the same object as the first index of the $toolbox array $toolbox[0] and represents the instance of class A. The same process is used to assign the $anothertool variable to the instance of class B (we just pass false as the parameter, instead of true).

Although not particularly useful as shown, this method of using reference-returning functions is great when working with search trees or other complex data structures, by allowing the developer to search through the data structure and return a reference to the exact piece of data in question!

References in Object Constructors

Now that we've covered almost all there is to discuss regarding references, it's time to get to what probably is the most confusing reference phenomena -- referencing an object from within its constructor. Consider the following class:

卡奥斯智能交互引擎
卡奥斯智能交互引擎

聚焦工业领域的AI搜索引擎工具

卡奥斯智能交互引擎 36
查看详情 卡奥斯智能交互引擎
<?php    class test {        function test($val) {            global $myref;            $myref = &$this;            $this->value = $val;        }        function printval() {            echo "The value of this class is '{$this->value}' <br>";        }        function setval($val) {            $this->value = $val;        }    }?>
登录后复制

Note that, in the constructor for this object, a global variable, $myref, is bound to a reference to $this (the pre-defined PHP reference to the object itself) and a member variable, $value, is set to the value of the passed parameter. When an instance of this class is created, a global variable, $myref, that points to this object will also be created. Hence, when this code is executed:

<?php    $myvar = new test('FooBar!');    $myvar->printval();    $myref->printval();?>
登录后复制

The output will be:

The value of this class is 'FooBar!'The value of this class is 'FooBar!'
登录后复制

Now, what if we were to change the member variable within our instance of this class? From what we have learned thus far from references, any changes made through either the $myvar->setval() or $myref->setval() member functions should effectively change both. However, when the code below is executed:

<?php    $myvar->setval('Changed the value from $myvar');    $myvar->printval();    $myref->printval();?>
登录后复制

The resulting output is as follows:

The value of this class is 'Change the value from $myvar'The value of this class is 'FooBar!'
登录后复制

Why didn't both change? The answer lies in when the object was first created. In PHP 4, the new statement does not return a reference by default. Rather, when the $myvar object was created, it returned a copy separate from the one referenced by the $myref variable. Thus, because they are separate instances of the same object, their variables are completely independent. To overcome this and achieve the desired result, we use the reference-binding operator when creating the objects, as shown:

<?php    $myvar =& new test('Foobar!');    $myvar->printval();    $myref->printval();    $myvar->setval('Now it works');    $myvar->printval();    $myref->printval();?>
登录后复制

And the output:

The value of this class is 'Foobar!'The value of this class is 'Foobar!'The value of this class is 'Now it works'The value of this class is 'Now it works'
登录后复制
That's All for Today

That's about everything there is to know about PHP references. From what I've shown you, you should be well on your way to using references to make your PHP scripts faster and more efficient, without using more code! Next week, I'll be changing gears and introducing some of the fundamental concepts around working with the browser to make your PHP pages more interactive and dynamic. See you then!

PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号