NYCPHP Meetup

NYPHP.org

[nycphp-talk] Access an element of a method that returns an ar ray

David Sklar sklar at sklar.com
Wed Jul 21 11:10:42 EDT 2004


That's just the way the parser works. If a function or method returns an 
array, you have to assign the array before you can access an individual 
element of it.

You can also do this (in either PHP 4 or PHP 5):

list($stooge1,$stooge2,$stooge3) = get_array();

or even, this, which saves the variable assignment but makes your code 
harder to read:

list(,$stooge2,) = get_array();

David

Joe Crawford wrote:

> David,
> 
> ok but why would they not allow array indices if they allow you to get
> strings, integers, etc...
> 
> Joe Crawford Jr.
> 
> 
> On Wed, 2004-07-21 at 09:44, David Sklar wrote:
> 
>>While you can do that nice chaining with object methods in PHP 5, you 
>>can't do it with array indices.
>>
>>This is OK in PHP 5:
>>
>><?php
>>
>>class Stooge {
>>     private $name = null;
>>     public function __construct($name) {
>>         $this->name = $name;
>>     }
>>     public function getName() {
>>         return $this->name;
>>     }
>>}
>>
>>function get_object() {
>>     return new Stooge('Moe');
>>}
>>
>>print get_object()->getName();
>>?>
>>
>>It prints "Moe". But this is not:
>>
>><?php
>>function get_array() {
>>     return array('Moe','Larry','Curly');
>>}
>>
>>
>>// these all are parse errors:
>>print get_array()[1];
>>print (get_array())[1];
>>print {get_array()}[1];
>>
>>?>
>>
>>David




More information about the talk mailing list