开发者

PHP If Shorthand Question

开发者 https://www.devze.com 2023-02-02 18:41 出处:网络
Hey all. I have a question regarding PHP\'s If shorthand. Is it possible with PHP\'s If shorthand to first include a file and then create a class from that file?

Hey all. I have a question regarding PHP's If shorthand. Is it possible with PHP's If shorthand to first include a file and then create a class from that file?

Here's what I mean:

$object = ($userpresent) ? include file; new firstclass : include different file; new otherclass;

I know 开发者_开发问答the above is incorrect. But is there a way to do this with shorthand?

Thanks


No, the conditional operator ?: does only allow expressions as operands but not statements:

The third group is the ternary operator: ?:. It should be used to select between two expressions depending on a third one, rather than to select two sentences or paths of execution. Surrounding ternary expressions with parentheses is a very good idea.

So your code will yield a syntax error.

Just use the standard if statement, that is way more readable:

if ($userpresent) {
    include file;
    $object = new firstclass;
} else {
    include different file;
    $object = new otherclass;
}


No. This is the ternary operation and it will return and assign a value (in your case back to $object). Doing anything else will not work.


I am trying to imagine why on earth you would need to do it using this syntax, but assuming you have your reasons, and it is okay to include both files, you should be able to do something like :

$object = ($first = include($file1) && $second = include($file2) && $userpresent) ? new firstclass : new otherclass;


The answers that answer "No" are wrong - it isn't pretty and you should be slapped for doing it, but it is perfectly possible.

$object = ($userpresent) ? (include "file" ? new firstclass : 0) : (include "different file" ?  new otherclass : 0);

This assumes that both files don't do custom return statements at the file level that evaluate to false (they almost never do) - if they do, replace the 0s with additional news ...

0

精彩评论

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