简体   繁体   中英

PHP ternary operator object assignment

I have an object:

$info = [
    'last_name' => $this->askForLastName(),
];

I am trying to read an environment variable in the form of env('ADMIN_LAST_NAME', null) and trying to use the ternary operator so that it should only call the function if the env variable does not exist.

For instance:

$info = [
    'last_name' => env('ADMIN_LAST_NAME', null)? env('ADMIN_LAST_NAME', null) : $this->askForLastName(),
];

Is this the correct way?

It might be better to use the ternary operator shortcut .

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

This way the env() function will be called just once (instead of twice):

$info = [
    'last_name' => env('ADMIN_LAST_NAME', null) ?: $this->askForLastName(),
];

It will work fine unless '' , null or false are valid admin last names.

That code should work, but it can be improved.

For one, since there is no alternative case for the true clause, you can use the shorthand ternary operator.

['last_name' => env('ADMIN_LAST_NAME', NULL) ?: $this->askForLastName()'] ;

Furthermore, while a null value will return false for an if clause, it's not very accurate or specific. If you want explicitly checking for null values, then use is_null . If you want null or false, use empty . In such a case, you will not be able to use the shorthand, as both the true / false clause must return a separate entity.

['last_name' => is_null(env('ADMIN_LAST_NAME', NULL)) ? $this->askForLastName() : env('ADMIN_LAST_NAME', NULL)]

You can take it a step further by getting rid of the multiple calls to env.

['last_name' => is_null(($adminLastName = env('ADMIN_LAST_NAME', NULL))) ? $this->askForLastName() : $adminLastName] ['last_name' => is_null(($adminLastName = env('ADMIN_LAST_NAME', NULL))) ? $this->askForLastName() : $adminLastName] .

It is a matter of code style and preference. Just keep it consistent throughout your codebase.

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