开发者

Reverse assignment in PHP ( LEFT to RIGHT )

I have the below condition:

if (isset($x)){
   $y_class = 'new value';
}else { 
   $z_class = 'new value';
}

Can I change the above if condition into a ternary? By this, I mean, is there any way to assign 开发者_C百科LEFT to RIGHT?

Imaginary code:

'new value' = (isset($x)) ? $y_class : $z_class;


Well, if $y_class and $z_class are hard-coded, you can do something like this, but this just makes your code less readable:

$var = isset($x) ? "y_class" : "z_class";
$$var = 'new value';

And of course this is still an assignment from right to left; as far as I know, there is no such syntax in the language which would allow assignment from left to right.


You could do that : ${(isset($x)?$y_class:$z_class)} = 'new value';

Mandatory link to the php documentation about variable variables.


Here's the cleanest implementation i could create. (Essentially a combination of the top 2 answers).

${(isset($x) ? 'y':'z'). '_class'} = 'new value';

I initially thought to use the list() language construct, its not as small but i implemented it anyway.

list($y_class, $z_class) = isset($x) ? ['new value', $z_class] : [ $y_class, 'new value'];

If it's possible that $y_class or $z_class are not set then you would have to do

list($y_class, $z_class) = isset($x) ? ['new value', isset($z_class) ? $z_class : null] : [ isset($y_class) ? $y_class : null, 'new value'];

both list examples would result in both the variables being assigned a value.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜