开发者

php: usage of define

in Yii they use this code:

 defined('YII_DEBUG') or define('YII_DEBUG',true);

i've never seen anyone wri开发者_开发百科te like this before (or). is this real php code or some syntax of yii?


Basically if defined("YII_DEBUG") evaluates to false, it will then define it. Kinda like:

mysql_connect() or die("DIE!!!!!");

It is actual PHP syntax, just not commonly used. It allows you to not have to write:

if(!defined("YII_DEBUG"))
{
    define("YII_DEBUG", true);
}

or even shorter

if(!defined("YII_DEBUG"))
    define("YII_DEBUG", true);

I'm guessing they used it to get rid of the if statement altogether. The second if statement without brackets would be a hazard for editing, and the first one might have taken up too much room for the developer.

Personally, I'd stick clear of this just because it isn't a commonly known feature. By using commonly known syntaxes (the if statements), other programmers don't have to wonder what it does.

(Although, I might now that I look at it. Seems straightforward and gets rid of unnessecary if clauses)


It's due to short circuit evaluation.

If defined('YII_DEBUG') returns false, it will try to evaluate the second expression to make the sentence true, defining YII_DEBUG constant as true.

The final result is that, if the constant were not defined, then define it as being true. If it's already defined (the value doesn't matter), then do nothing (as the first expression is true, the second expression does not need to be evaluated for the expression to be true).


Pretty straightforward - the 'or' operator is efficient in that it will only evaluate the second part of the statement if it needs to. So if the first part evaluates to true (the constant is already defined), then the define() call isn't executed.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜