Re: echo returnArray()['a']; // workaround
| From: | Ray Hauge | Date: | Thu, 28 Feb 2008 19:36:09 +0000 |
| Subject: | Re: echo returnArray()['a']; // workaround | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-270639@lists.php.net to get a copy of this message | ||
Nathan Nobbe wrote:
all, as we have discussed previously, php does not have support for retrieving array values on the same line in which they are returned. i have created a simple workaround, and would like to share. first there is the class (w/ other features omitted for the post) <?php class ArrayClass {That's pretty cool. I wasn't sure if it would work with numerically indexed arrays, so I tried: // sillyFunc returns array(0=>1, 1=>2); ArrayClass::create(sillyFunc())->{"0"} I just tested it, and that works. If you leave off the curly braces and quotes, then you obviously get a parse error. The curly braces are necessary. -- Ray Hauge www.primateapplications.comprivate $theArray = null;private function __construct($theArray) { if(!is_array($theArray)) { throw UnexpectedValueException('theArray must be an array!'); } $this->theArray = $theArray; }public static function create($theArray) { return new ArrayClass($theArray); }public function __get($name) { if($this->isValidKey($name)) { return $this->theArray[$name]; } }private function isValidKey($name) { $isValidKey = false; if(array_key_exists($name, $this->theArray)) { $isValidKey = true; } return $isValidKey; }} ?> and then there is the example, <?php include('ArrayClass.php'); function sillyFunc() {return array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);} echo ArrayClass::create(sillyFunc())->a . PHP_EOL; ?> notice what would be echo sillyFunc()['a'] . PHP_EOL; becomes what you see above. -nathan ps. sorry for all the extra newlines; im trying to work w/ the alterations the list server is applying to my posts so bear w/ me :D