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

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

 



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

[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