PHP中的引用

Jun 23, 2016 pm 02:32 PM

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();?>
Copier après la connexion

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();?>
Copier après la connexion

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

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:

<?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;        }    }?>
Copier après la connexion

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();?>
Copier après la connexion

The output will be:

The value of this class is 'FooBar!'The value of this class is 'FooBar!'
Copier après la connexion

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();?>
Copier après la connexion

The resulting output is as follows:

The value of this class is 'Change the value from $myvar'The value of this class is 'FooBar!'
Copier après la connexion

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();?>
Copier après la connexion

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'
Copier après la connexion
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!

Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn

Article chaud

Repo: Comment relancer ses coéquipiers
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
Combien de temps faut-il pour battre Split Fiction?
3 Il y a quelques semaines By DDD
R.E.P.O. Crystals d'énergie expliqués et ce qu'ils font (cristal jaune)
1 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: Comment obtenir des graines géantes
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌

Article chaud

Repo: Comment relancer ses coéquipiers
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
Combien de temps faut-il pour battre Split Fiction?
3 Il y a quelques semaines By DDD
R.E.P.O. Crystals d'énergie expliqués et ce qu'ils font (cristal jaune)
1 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: Comment obtenir des graines géantes
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌

Tags d'article chaud

Bloc-notes++7.3.1

Bloc-notes++7.3.1

Éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise

SublimeText3 version chinoise

Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1

Envoyer Studio 13.0.1

Puissant environnement de développement intégré PHP

Dreamweaver CS6

Dreamweaver CS6

Outils de développement Web visuel

SublimeText3 version Mac

SublimeText3 version Mac

Logiciel d'édition de code au niveau de Dieu (SublimeText3)

11 meilleurs scripts de raccourcissement d'URL PHP (gratuit et premium) 11 meilleurs scripts de raccourcissement d'URL PHP (gratuit et premium) Mar 03, 2025 am 10:49 AM

11 meilleurs scripts de raccourcissement d'URL PHP (gratuit et premium)

Introduction à l'API Instagram Introduction à l'API Instagram Mar 02, 2025 am 09:32 AM

Introduction à l'API Instagram

Travailler avec les données de session Flash dans Laravel Travailler avec les données de session Flash dans Laravel Mar 12, 2025 pm 05:08 PM

Travailler avec les données de session Flash dans Laravel

Misque de réponse HTTP simplifié dans les tests Laravel Misque de réponse HTTP simplifié dans les tests Laravel Mar 12, 2025 pm 05:09 PM

Misque de réponse HTTP simplifié dans les tests Laravel

Curl dans PHP: Comment utiliser l'extension PHP Curl dans les API REST Curl dans PHP: Comment utiliser l'extension PHP Curl dans les API REST Mar 14, 2025 am 11:42 AM

Curl dans PHP: Comment utiliser l'extension PHP Curl dans les API REST

Construisez une application React avec un Laravel Back End: Partie 2, React Construisez une application React avec un Laravel Back End: Partie 2, React Mar 04, 2025 am 09:33 AM

Construisez une application React avec un Laravel Back End: Partie 2, React

12 meilleurs scripts de chat PHP sur Codecanyon 12 meilleurs scripts de chat PHP sur Codecanyon Mar 13, 2025 pm 12:08 PM

12 meilleurs scripts de chat PHP sur Codecanyon

Notifications à Laravel Notifications à Laravel Mar 04, 2025 am 09:22 AM

Notifications à Laravel

See all articles