Tricks for shortening PHP code? [closed]
I am looking for neat tricks that can be used to compress PHP code while working on a fun project. Let me share some of the ones I know so far.
Using straight conditionals with no brackets
if(TRUE)yes();else no();
You can acquire and validate variables in one line
if(!($value=function($input)||empty($value->foo))return FALSE;
You can check a value (and default) using the Ternary Operator in PHP 5.3
$foo = $bar?:NULL;
Return boolean values for conditions
return!$foo;
And one I place at the top of my PHP classes to protect them from direct access - straight boolean checks:
defined('BASE_DIR')||die();
What is the most valuable PHP trick you have learned to reduce space used?
Update: There seems to be some concern about how unreadable compressed code is. I concur, do not write code like this normally. However, I'm attempting to compress code into very small tidbits for fun and I want to know all the options I have to compress a function into a few dozen characters.
Next time please answer the question and don't surmise about my ignorance of best-practices.
The best trick I know for shortening PHP code is to not shorten PHP (or any language) code.
All of the tips you've mentioned are things I would never use, because readability is much, much more important than making your file size smaller.
Let's look at your first example:
if(TRUE)yes();else no();
If we were to write this out in "longhand", it would look like this:
if (TRUE) {
yes();
} else {
no();
}
You're saving a grand total of 14 bytes, but at what cost?
If you come back to that in two months (and you will, even if you don't think so now), which of those two code samples is going to be more obvious to you?
Storage space is cheap, programmer time is not.
There isn't really any benefit to shortening PHP code in this way, since it is hosted on a server. A 10K and a 5K script (that do the same thing) won't look any different to an end user, because the result may be the same size. A PHP script itself isn't served, unlike JavaScript and HTML where this kind of thing is actually useful. Readability is much more important than space-saving tricks.
精彩评论