2

in Yii they use this code:

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

i've never seen anyone write like this before (or). is this real php code or some syntax of yii?

3 Answers 3

5

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)

Sign up to request clarification or add additional context in comments.

2 Comments

It looks like nice clean code. I can see myself using this syntax somewhere in the future.
i have also seen defined(CONSTANT) ? null : define('CONSTANT', true); that is also very clean
1

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).

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.