PHP: Using the ternary operator for something else than assignments – valid use case? -


unfortunately haven't found official resource on this.

is allowed use ternary operator this, shorten , if/else statement:

(isset($somevar) ? $this->setmyvar('something') : $this->setmyvar('something else')); 

in php documentation, ternary operator explained example:

$action = (empty($_post['action'])) ? 'standard' : $_post['action']; 

this makes me believe use case might work, not valid because setter function not return anything.

yes, can. php doc:

[...] ternary operator expression, , [...] doesn't evaluate variable, result of expression.

that quoted, although ternary used assigning values, can use suggested because function call expression appropriate function evaluated (and therefore executed).

if setter function return value, not assigned , therefore lost. however, since said setter doesn't return anything, whole ternary operator evaluate nothing , return nothing. that's fine.

if more readable regular if/else different story. when working in team, suggest rather stick regular if/else.

or, how going syntax, more common?

$this->myvar = isset($somevar) ? 'something' : 'something else'; 

or, using setter:

$this->setmyvar(isset($somevar) ? 'something' : 'something else'); 

Comments

Popular posts from this blog

jquery - How do you format the date used in the popover widget title of FullCalendar? -

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -