Re: echo returnArray()['a']; // workaround

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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 {
    private $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


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.com

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux