Tuesday 15 April 2014

PHP, Why doesn't anyone use the ?: operator? -



PHP, Why doesn't anyone use the ?: operator? -

i cant seem find give-and-take this.

in javascript check if exists, , utilize default if doesn't this:

var myvariable = mysetting || 3

in php understand, same thing can done this:

$myvariable = $mysetting ?: 3;

am off on this? understand implications of not using isset() , not_empty() , that, if want know if variable exists , truthy otherwise utilize default - should work think. syntax have hidden bad things it?

because doesn't work. code still throw notice notice: undefined variable: mysetting in c:\wamp\www\x.php on line, might visible user, depending on php settings. apart that, work. if notices suppressed, end result correct.

so, around that, can either utilize isset, isn't function, language construct, , designed check:

$myvariable = isset($mysetting)? $mysetting: 3;

or can suppress notice using @ operator:

$myvariable = @$mysetting ?: 3;

for specific case, maybe it's acceptable, in general utilize of @ frowned upon many. personally, rather utilize couple more characters , create sense less 'dirty', it's matter of opinion.

another reason why people may not utilize it, it's relatively new (php 5.3). not might know of new syntax or comfortable it. have been used isset years, , old habits die hard.

php ternary-operator

No comments:

Post a Comment