简体   繁体   中英

PHP inline access to Array elements returned by an Object Method

Say we have the object $teams (an associative array) containing an object that provides the method getMembers() which returns an Array as follows:

$membersArray = $teams['blueteam']->getMembers();

If I want to then access individual members, I may do so as follows:

$membersArray[1];

Why can't I perform the access in-line as follows, and is there a proper way to do so in PHP?

$membersArray = $teams['blueteam']->getMembers()[1];

Rather than try to access it like that, why not make an alternative method called getMember() which accepts a parameter for the array index. For example:

function getMember( $index )
{
    return $this->members[$index];
}

This makes your code a little more self-documenting by indicating getMembers will return an array of members, where getMember() will only return a single array element.

在PHP 5.4.0中添加了对此的支持:

$membersArray = $teams['blueteam']->getMembers()[1];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM