搜尋

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

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;        }    }?>

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!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
超越炒作:評估當今PHP的角色超越炒作:評估當今PHP的角色Apr 12, 2025 am 12:17 AM

PHP在現代編程中仍然是一個強大且廣泛使用的工具,尤其在web開發領域。 1)PHP易用且與數據庫集成無縫,是許多開發者的首選。 2)它支持動態內容生成和麵向對象編程,適合快速創建和維護網站。 3)PHP的性能可以通過緩存和優化數據庫查詢來提升,其廣泛的社區和豐富生態系統使其在當今技術棧中仍具重要地位。

PHP中的弱參考是什麼?什麼時候有用?PHP中的弱參考是什麼?什麼時候有用?Apr 12, 2025 am 12:13 AM

在PHP中,弱引用是通過WeakReference類實現的,不會阻止垃圾回收器回收對象。弱引用適用於緩存系統和事件監聽器等場景,需注意其不能保證對象存活,且垃圾回收可能延遲。

解釋PHP中的__ Invoke Magic方法。解釋PHP中的__ Invoke Magic方法。Apr 12, 2025 am 12:07 AM

\_\_invoke方法允許對象像函數一樣被調用。 1.定義\_\_invoke方法使對象可被調用。 2.使用$obj(...)語法時,PHP會執行\_\_invoke方法。 3.適用於日誌記錄和計算器等場景,提高代碼靈活性和可讀性。

解釋PHP 8.1中的纖維以進行並發。解釋PHP 8.1中的纖維以進行並發。Apr 12, 2025 am 12:05 AM

Fibers在PHP8.1中引入,提升了並發處理能力。 1)Fibers是一種輕量級的並發模型,類似於協程。 2)它們允許開發者手動控制任務的執行流,適合處理I/O密集型任務。 3)使用Fibers可以編寫更高效、響應性更強的代碼。

PHP社區:資源,支持和發展PHP社區:資源,支持和發展Apr 12, 2025 am 12:04 AM

PHP社區提供了豐富的資源和支持,幫助開發者成長。 1)資源包括官方文檔、教程、博客和開源項目如Laravel和Symfony。 2)支持可以通過StackOverflow、Reddit和Slack頻道獲得。 3)開發動態可以通過關注RFC了解。 4)融入社區可以通過積極參與、貢獻代碼和學習分享來實現。

PHP與Python:了解差異PHP與Python:了解差異Apr 11, 2025 am 12:15 AM

PHP和Python各有優勢,選擇應基於項目需求。 1.PHP適合web開發,語法簡單,執行效率高。 2.Python適用於數據科學和機器學習,語法簡潔,庫豐富。

php:死亡還是簡單地適應?php:死亡還是簡單地適應?Apr 11, 2025 am 12:13 AM

PHP不是在消亡,而是在不斷適應和進化。 1)PHP從1994年起經歷多次版本迭代,適應新技術趨勢。 2)目前廣泛應用於電子商務、內容管理系統等領域。 3)PHP8引入JIT編譯器等功能,提升性能和現代化。 4)使用OPcache和遵循PSR-12標準可優化性能和代碼質量。

PHP的未來:改編和創新PHP的未來:改編和創新Apr 11, 2025 am 12:01 AM

PHP的未來將通過適應新技術趨勢和引入創新特性來實現:1)適應云計算、容器化和微服務架構,支持Docker和Kubernetes;2)引入JIT編譯器和枚舉類型,提升性能和數據處理效率;3)持續優化性能和推廣最佳實踐。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
4 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版