PHP function Return Reference example

Source: Internet
Author: User

<?phpclass test{public $userCache;p ublic function init () {for ($i = 0; $i < 5; $i + +) {$user = array (' name ' = ' joe$i ') , ' age ' = + $i,); $this->usercache[] = $user;}}  Public Function Displayarray ($arr = ") {if (GetType ($arr)!== ' array ') $arr = $this->usercache;foreach ($arr as $k + = $v) {echo "$k:";p rint_r ($v); echo "\ n";}} Public Function &getuser ($UID)//function return reference {if (Isset ($this->usercache[$uid])) {return $user = & $this usercache[$uid];//$user Fetch reference (cannot be broken here)}else{echo "Create a new user:\n"; $user = Array (' name ' = ' xxy ', ' age ' =>66); $ this->usercache[$uid] = $user; return $user = & $this->usercache[$uid];}} Public Function ModifyUser ($uid) {//$user = $this->getuser ($uid);//non-reference call $user = & $this->getuser ($UID);// Reference calls $this->displayarray ($user); echo "------------------\ n"; $user [' name '] = ' jjoe ';//Modify the return value $this-> Displayarray ($user); $this->displayarray ();//You can see that the referenced object value has been modified}} $a = new Test (); $a->init (); $a->modifyuser ( 12);

  

Operation Result:

[Email protected] server]$ PHP test.php Create a new user:name:xxyage:66------------------Name:jjoeage:660:array (
   [name] = Joe0    [age] = 1:array (    [name] = Joe1 [age    ] = 2:array (    [name] = joe2< C5/>[age] 3:array (    [name] = Joe3    [age] = +) 4:array (    [name] = Joe4    [age] + 27) 1 2:array (    [name] = Jjoe    [age] = 66)

  

  

PHP function Return Reference example

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.