note 96860 added to language.references.return

From: Date: Fri, 19 Mar 2010 14:18:05 +0000
Subject: note 96860 added to language.references.return
Groups: php.notes 
Request: Send a blank email to php-notes+get-167198@lists.php.net to get a copy of this message
When returning reference to the object member which is instantiated inside the function, the object is destructed upon returning (which is a problem). It's easier to see the code: <?php class MemcacheArray { public $data; ... /** * Super-clever one line cache reading AND WRITING! * Usage $data = &MemcacheArray::getData(__METHOD__); * Hopefully PHP will know that $this->data is still used * and will call destructor after data changes. * Ooops, it's not the case. * * @return unknown */ function &getData($file, $expire = 3600) { $o = new MemcacheArray($file, $expire); return $o->data; } ?> Here, destructor is called upon return() and the reference becomes a normal variable. My solution is to store objects in a pool until the final exit(), but I don't like it. Any other ideas? <?php protected static $instances = array(); function &getData($file, $expire = 3600) { $o = new MemcacheArray($file, $expire); self::$instances[$file] = $o; // keep object from destructing too early return $o->data; } ?> ---- Server IP: 69.147.83.197 Probable Submitter: 84.233.202.2 ---- Manual Page -- http://www.php.net/manual/en/language.references.return.php Edit -- https://master.php.net/note/edit/96860 Del: integrated -- https://master.php.net/note/delete/96860/integrated Del: useless -- https://master.php.net/note/delete/96860/useless Del: bad code -- https://master.php.net/note/delete/96860/bad+code Del: spam -- https://master.php.net/note/delete/96860/spam Del: non-english -- https://master.php.net/note/delete/96860/non-english Del: in docs -- https://master.php.net/note/delete/96860/in+docs Del: other reasons-- https://master.php.net/note/delete/96860 Reject -- https://master.php.net/note/reject/96860 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#167198) next »