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

From: Date: Thu, 28 Feb 2008 21:22:41 +0000
Subject: Re: echo returnArray()['a']; // workaround
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-270663@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 {
    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
So, I guess my question would be, why not take it one level deeper. <?php include('ArrayClass.php'); function sillyFunc() {
    return ArrayClass::create(array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4));
} echo sillyFunc()->a . PHP_EOL; ?> -- Jim Lucas "Some men are born to greatness, some achieve greatness, and some have greatness thrust upon them." Twelfth Night, Act II, Scene V by William Shakespeare

« previous php.general (#270663) next »