开发者

PHP: Handling return of function without storing?

Let's say that I have a library in my application that returns an array. Is it possible to access the array without, in beforehand, storing it as an variable in my scope?

The below shown code clearly doesnt work, but is something similar to this possible?

Example of what I would like to do:

if(isSet($myLibrary->create_nice_array()['element'])) {
    //...
}

Example of what I need to do right now:

$temp_array = $myLibrary->create_nice_array();

if(isSe开发者_如何学运维t($temp_array['element'])) {
    //...
}


In general, it's possible. However, you are using the isset() function:

bool isset ( mixed $var [, mixed $... ] )
Determine if a variable is set and is not NULL.

Warning: isset() only works with variables as passing anything else will result in a parse error. For checking if constants are set use the defined() function.

Which makes perfect sense.


You aren't the only one who wishes they could do this in PHP!

You have to assign the output to a variable and then manipulate the variable.


The isset issue:

isset can only take variables as parameters, not function returns.

The array access issue:

I think it was said pretty well here.

Because of how PHP is defined, there is no ability to have structures like: [$a]() or ()[$a]. It simply can't be done


You could use

if(array_key_exists('element', $myLibrary->create_nice_array())) {
    //...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜