[ACCEPTED]-Hidden Features of PHP?-hidden-features

Accepted answer
Score: 328

Documentation. The documentation gets my vote. I haven't encountered 4 a more thorough online documentation for 3 a programming language - everything else 2 I have to piece together from various websites 1 and man pages.

Score: 179

Arrays. Judging from the answers to this question 10 I don't think people fully appreciate just 9 how easy and useful Arrays in PHP are. PHP 8 Arrays act as lists, maps, stacks and generic 7 data structures all at the same time. Arrays 6 are implemented in the language core and 5 are used all over the place which results 4 in good CPU cache locality. Perl and Python 3 both use separate language constructs for 2 lists and maps resulting in more copying 1 and potentially confusing transformations.

Score: 167

Stream Handlers allow you to extend the "FileSystem" with 4 logic that as far as I know is quite difficult 3 to do in most other languages.

For example 2 with the MS-Excel Stream handler you can create a MS Excel file 1 in the following way:

$fp = fopen("xlsfile://tmp/test.xls", "wb");
if (!is_resource($fp)) { 
    die("Cannot open excel file");

$data= array(
    array("Name" => "Bob Loblaw", "Age" => 50),  
    array("Name" => "Popo Jijo", "Age" => 75),  
    array("Name" => "Tiny Tim", "Age" => 90)

fwrite($fp, serialize($data));
Score: 131

Magic Methods are fall-through methods that get called 8 whenever you invoke a method that doesn't 7 exist or assign or read a property that 6 doesn't exist, among other things.

interface AllMagicMethods {
    // accessing undefined or invisible (e.g. private) properties
    public function __get($fieldName);
    public function __set($fieldName, $value);
    public function __isset($fieldName);
    public function __unset($fieldName);

    // calling undefined or invisible (e.g. private) methods
    public function __call($funcName, $args);
    public static function __callStatic($funcName, $args); // as of PHP 5.3

    // on serialize() / unserialize()
    public function __sleep();
    public function __wakeup();

    // conversion to string (e.g. with (string) $obj, echo $obj, strlen($obj), ...)
    public function __toString();

    // calling the object like a function (e.g. $obj($arg, $arg2))
    public function __invoke($arguments, $...);

    // called on var_export()
    public static function __set_state($array);

A C++ developer 5 here might notice, that PHP allows overloading 4 some operators, e.g. () or (string). Actually PHP 3 allows overloading even more, for example 2 the [] operator (ArrayAccess), the foreach language construct 1 (Iterator and IteratorAggregate) and the count function (Countable).

Score: 95

The standard class is a neat container. I only learned 4 about it recently.

Instead of using an array 3 to hold serveral attributes

$person = array();
$person['name'] = 'bob';
$person['age'] = 5;

You can use a 2 standard class

$person = new stdClass();
$person->name = 'bob';
$person->age = 5;

This is particularly helpful 1 when accessing these variables in a string

$string = $person['name'] . ' is ' . $person['age'] . ' years old.';
// vs
$string = "$person->name is $person->age years old.";
Score: 90

Include files can have a return value you can assign to a variable.

// config.php
return array(
    'db' => array(
        'host' => 'example.org',
        'user' => 'usr',
        // ...
    // ...

// index.php
$config = include 'config.php';
echo $config['db']['host']; // example.org


Score: 83

You can take advantage of the fact that 4 the or operator has lower precedence than 3 = to do this:

$page = (int) @$_GET['page'] 
  or $page = 1;

If the value of the first assignment 2 evaluates to true, the second assignment is 1 ignored. Another example:

$record = get_record($id) 
  or throw new Exception("...");
Score: 80

__autoload() (class-) files aided by set_include_path().

In PHP5 it is 8 now unnecessary to specify long lists of 7 "include_once" statements when 6 doing decent OOP.

Just define a small set 5 of directory in which class-library files 4 are sanely structured, and set the auto 3 include path:

set_include_path(get_include_path() . PATH_SEPARATOR . '../libs/');`

Now the __autoload() routine:

function __autoload($classname) {
    // every class is stored in a file "libs/classname.class.php"

    // note: temporary alter error_reporting to prevent WARNINGS
    // Do not suppress errors with a @ - syntax errors will fail silently!

    include_once($classname . '.class.php');

Now PHP will 2 automagically include the needed files on-demand, conserving 1 parsing time and memory.

Score: 76

Variable variables and functions without a doubt!

$foo = 'bar';
$bar = 'foobar';
echo $$foo;    //This outputs foobar

function bar() {
    echo 'Hello world!';

function foobar() {
    echo 'What a wonderful world!';
$foo();    //This outputs Hello world!
$$foo();    //This outputs What a wonderful world!

The same concept applies 5 to object parameters ($some_object->$some_variable);

Very, very 4 nice. Make's coding with loops and patterns 3 very easy, and it's faster and more under 2 control than eval (Thanx @Ross & @Joshi 1 Spawnbrood!).t

Score: 76

Easiness. The greatest feature is how easy it is 15 for new developers to sit down and write 14 "working" scripts and understand the code.

The 13 worst feature is how easy it is for new 12 developers to sit down and write "working" scripts 11 and think they understand the code.

The openness of the community surrounding 10 PHP and the massive amounts of PHP projects 9 available as open-source is a lot less intimidating 8 for someone entering the development world 7 and like you, can be a stepping stone into 6 more mature languages.

I won't debate the 5 technical things as many before me have 4 but if you look at PHP as a community rather 3 than a web language, a community that clearly 2 embraced you when you started developing, the 1 benefits really speak for themselves.

Score: 68

You can use functions with a undefined number of arguments using the func_get_args().


function test() {

    $args = func_get_args();
    echo $args[2]; // will print 'd'
    echo $args[1]; // will print 3




Score: 67

I love remote files. For web development, this kind 12 of feature is exceptionally useful.

Need 11 to work with the contents of a web page? A 10 simple

$fp = fopen('http://example.com');

and you've got a file handle ready 9 to go, just like any other normal file.

Or 8 how about reading a remote file or web page 7 directly in to a string?

$str = file_get_contents('http://example.com/file');

The usefulness 6 of this particular method is hard to overstate.

Want 5 to analyze a remote image? How about doing 4 it via FTP?

$imageInfo = getimagesize('ftp://user:password@ftp.example.com/image/name.jpg');

Almost any PHP function that 3 works with files can work with a remote 2 file. You can even include() or require() code files remotely 1 this way.

Score: 63


It's extremely fast, so much that you would 19 be amazed. Internally it probably uses 18 some crazy b-tree type structure to arrange 17 your matches by their common prefixes. I 16 use it with over 200 find and replace strings 15 and it still goes through 1MB in less than 14 100ms. For all but trivially small strings 13 strtr() is even significantly faster than 12 strtolower() at doing the exact same thing, even 11 taking character set into account. You 10 could probably write an entire parser using 9 successive strtr calls and it'd be faster 8 than the usual regular expression match, figure 7 out token type, output this or that, next 6 regular expression kind of thing.

I was writing 5 a text normaliser for splitting text into 4 words, lowercasing, removing punctuation 3 etc and strtr was my Swiss army knife, it 2 beat the pants off regular expressions or 1 even str_replace().

Score: 61

One not so well known feature of PHP is 6 extract(), a function that unpacks an associative 5 array into the local namespace. This probably 4 exists for the autoglobal abormination but 3 is very useful for templating:

function render_template($template_name, $context, $as_string=false)
    if ($as_string)
    include TEMPLATE_DIR . '/' . $template_name;
    if ($as_string)
        return ob_get_clean();

Now you can 2 use render_template('index.html', array('foo' => 'bar')) and only $foo with the value "bar" appears in 1 the template.

Score: 52

Range() isn't hidden per se, but I still see a 2 lot of people iterating with:

for ($i=0; $i < $x; $i++) { 
    // code...

when they could 1 be using:

foreach (range(0, 12) as $number) {
    // ...

And you can do simple things like

foreach (range(date("Y"), date("Y")+20) as $i)
print "\t<option value=\"{$i}\">{$i}</option>\n";
Score: 44

PHP enabled webspace is usually less expensive than something 2 with (asp).net. You might call that a feature 1 ;-)

Score: 42

One nice feature of PHP is the CLI. It's not 3 so "promoted" in the documentation but if 2 you need routine scripts / console apps, using 1 cron + php cli is really fast to develop!

Score: 42

The static keyword is useful outside of a OOP 14 standpoint. You can quickly and easily implement 13 'memoization' or function caching with something 12 as simple as:

function foo($arg1)
    static $cache;

    if( !isset($cache[md5($arg1)]) )
        // Do the work here
        $cache[md5($arg1)] = $results;

    return $cache[md5($arg1)];

The static keyword creates a variable 11 that persists only within the scope of that 10 function past the execution. This technique 9 is great for functions that hit the database 8 like get_all_books_by_id(...) or get_all_categories(...) that you would call more than 7 once during a page load.

Caveat: Make sure you find 6 out the best way to make a key for your 5 hash, in just about every circumstance the 4 md5(...) above is NOT a good decision (speed and 3 output length issues), I used it for illustrative 2 purposes. sprintf('%u', crc32(...)) or spl_object_hash(...) may be much better depending 1 on the context.

Score: 40

Then "and print" trick

<?php $flag and print "Blah" ?>

Will echo Blah if $flag is true. DOES NOT 3 WORK WITH ECHO.

This is very handy in template 2 and replace the ? : that are not really 1 easy to read.

Score: 37

You can use minus character in variable names like this:

class style
  function set_bg_colour($c)
    $this->{'background-color'} = $c;

Why use it? No idea: maybe 2 for a CSS model? Or some weird JSON you 1 need to output. It's an odd feature :)

Score: 34

HEREDOC syntax is my favourite hidden feature. Always 4 difficult to find as you can't Google for 3 <<< but it stops you having to 2 escape large chunks of HTML and still allows 1 you to drop variables into the stream.

echo <<<EOM
  <div id="someblock">
    <img src="{$file}" />
Score: 34

Probably not many know that it is possible 3 to specify constant "variables" as default 2 values for function parameters:

function myFunc($param1, $param2 = MY_CONST)

Strings can be used 1 as if they were arrays:

$str = 'hell o World';
echo $str; //outputs: "hell o World"

$str[0] = 'H';
echo $str; //outputs: "Hell o World"

$str[4] = null;
echo $str; //outputs: "Hello World"
Score: 33

The single most useful thing about PHP code 10 is that if I don't quite understand a function 9 I see I can look it up by using a browser 8 and typing:


Last month I saw the "range" function 7 in some code. It's one of the hundreds of 6 functions I'd managed to never use but turn 5 out to be really useful:


That url is an alias 4 for http://us2.php.net/manual/en/function.range.php. That simple idea, of mapping functions and keywords to urls, is awesome.

I 3 wish other languages, frameworks, databases, operating 2 systems has as simple a mechanism for looking 1 up documentation.

Score: 30

Fast block comments

    die('You shall not pass!');

    die('You shall not pass!');

These comments allow you to toggle if a 1 code block is commented with one character.

Score: 29

My list.. most of them fall more under the 15 "hidden features" than the "favorite features" (I 14 hope!), and not all are useful, but .. yeah.

// swap values. any number of vars works, obviously  
list($a, $b) = array($b, $a);

// nested list() calls "fill" variables from multidim arrays:  
$arr = array(  
  array('aaaa', 'bbb'),  
  array('cc', 'd')  
list(list($a, $b), list($c, $d)) = $arr;  
echo "$a $b $c $d"; // -> aaaa bbb cc d  

// list() values to arrays  
while (list($arr1[], $arr2[], $arr3[]) = mysql_fetch_row($res)) { .. }  
// or get columns from a matrix  
foreach($data as $row) list($col_1[], $col_2[], $col_3[]) = $row;

// abusing the ternary operator to set other variables as a side effect:  
$foo = $condition ? 'Yes' . (($bar = 'right') && false) : 'No' . (($bar = 'left') && false);  
// boolean False cast to string for concatenation becomes an empty string ''.  
// you can also use list() but that's so boring ;-)  
list($foo, $bar) = $condition ? array('Yes', 'right') : array('No', 'left');

You 13 can nest ternary operators too, comes in 12 handy sometimes.

// the strings' "Complex syntax" allows for *weird* stuff.  
// given $i = 3, if $custom is true, set $foo to $P['size3'], else to $C['size3']:  
$foo = ${$custom?'P':'C'}['size'.$i];  
$foo = $custom?$P['size'.$i]:$C['size'.$i]; // does the same, but it's too long ;-)  
// similarly, splitting an array $all_rows into two arrays $data0 and $data1 based  
// on some field 'active' in the sub-arrays:  
foreach ($all_rows as $row) ${'data'.($row['active']?1:0)}[] = $row;

// slight adaption from another answer here, I had to try out what else you could  
// abuse as variable names.. turns out, way too much...  
$string = 'f.> <!-? o+';  
${$string} = 'asdfasf';  
echo ${$string}; // -> 'asdfasf'  
echo $GLOBALS['f.> <!-? o+']; // -> 'asdfasf'  
// (don't do this. srsly.)

${''} = 456;  
echo ${''}; // -> 456  
echo $GLOBALS['']; // -> 456  
// I have no idea.  

Right, I'll stop for now 11 :-)

Hmm, it's been a while..

// just discovered you can comment the hell out of php:
$q/* snarf */=/* quux */$_GET/* foo */[/* bar */'q'/* bazz */]/* yadda */;

So, just discovered 10 you can pass any string as a method name 9 IF you enclose it with curly brackets. You 8 can't define any string as a method alas, but 7 you can catch them with __call(), and process 6 them further as needed. Hmmm....

class foo {
  function __call($func, $args) {
    eval ($func);

$x = new foo;
$x->{'foreach(range(1, 10) as $i) {echo $i."\n";}'}();

Found this 5 little gem in Reddit comments:

$foo = 'abcde';
$strlen = 'strlen';
echo "$foo is {$strlen($foo)} characters long."; // "abcde is 5 characters long."

You can't 4 call functions inside {} directly like this, but 3 you can use variables-holding-the-function-name 2 and call those! (*and* you can use variable 1 variables on it, too)

Score: 26

Array manipulation.
Tons of tools for working with and manipulating 3 arrays. It may not be unique to PHP, but 2 I've never worked with a language that made 1 it so easy.

Score: 26

I'm a bit like you, I've coded PHP for over 12 8 years. I had to take a .NET/C# course 11 about a year ago and I really enjoyed the 10 C# language (hated ASP.NET) but it made 9 me a better PHP developer.

PHP as a language 8 is pretty poor, but, I'm extremely quick 7 with it and the LAMP stack is awesome. The 6 end product far outweighs the sum of the 5 parts.

That said, in answer to your question:


I 4 love the SPL, the collection class in C# was 3 something that I liked as soon as I started 2 with it. Now I can have my cake and eat 1 it.


Score: 24

I'm a little surprised no-one has mentioned 11 it yet, but one of my favourite tricks with 10 arrays is using the plus operator. It is 9 a little bit like array_merge() but a little simpler. I've 8 found it's usually what I want. In effect, it 7 takes all the entries in the RHS and makes 6 them appear in a copy of the LHS, overwriting 5 as necessary (i.e. it's non-commutative). Very 4 useful for starting with a "default" array 3 and adding some real values all in one hit, whilst 2 leaving default values in place for values 1 not provided.

Code sample requested:

// Set the normal defaults.
$control_defaults = array( 'type' => 'text', 'size' => 30 );

// ... many lines later ...

$control_5 = $control_defaults + array( 'name' => 'surname', 'size' => 40 );
// This is the same as:
// $control_5 = array( 'type' => 'text', 'name' => 'surname', 'size' => 40 );
Score: 21

Here's one, I like how setting default values on function parameters that aren't supplied 1 is much easier:

function MyMethod($VarICareAbout, $VarIDontCareAbout = 'yippie') { }
Score: 21

Quick and dirty is the default.
The language is filled 8 with useful shortcuts, This makes PHP the 7 perfect candidate for (small) projects that 6 have a short time-to-market. Not that clean 5 PHP code is impossible, it just takes some 4 extra effort and experience.

But I love PHP 3 because it lets me express what I want without 2 typing an essay.


if (preg_match("/cat/","one cat")) {
   // do something


import java.util.regex.*;
Pattern p = Pattern.compile("cat");
Matcher m = p.matcher("one cat")
if (m.find()) {
  // do something

And yes, that includes 1 not typing Int.

Score: 16

You can use break N; to exit nested loops (to compensate 2 for the lack of goto). For example

for (int i=0; i<100; i++) {
    foreach ($myarr as $item) {
        if ($item['name'] == 'abort')
            break 2;

More info 1 here - http://php.net/manual/en/control-structures.break.php

Score: 16

Output buffering via ob_start() is far more useful than 8 most realize. The first hidden feature here 7 is that ob_start accepts a callback:

function twiterize($text) {
    // Replace @somename with the full twitter handle
    return preg_replace("(\s+)@(\w)+(\s+)", "http://www.twitter.com/${2}", $text);


Secondly, you 6 can nest output buffers... Using the previous 5 example:

 // ... 
   // ...
 // ... 

Help contents, text ads, dictionary/index 4 functionality, linkify, link-redirection 3 for tracking purposes, templating engine, all 2 these things are very easy by using different 1 combinations of these 2 things.

Score: 15

Actually, you're not quite right about that 11 you cannot specify what types a method expects, it 10 does work as you'd expect.

function foo ( array $param0, stdClass $param1 );

Note: This only works 9 for 'array' and object names.

And so on, and 8 you can even pass in your own classes as 7 expected parameters. Calling the methods/functions 6 with something else will result in a fatal 5 error.

Another hint about a good intellisense 4 in PHP. We use ZendStudio and it will actually 3 work a lot better if you write good PHPDocs 2 for your methods, it will look into those 1 when hinting.

Score: 13

Besides instant access to start coding away 3 at anything you need for a website?

Besides 2 magic methods and reflections, some interesting 1 functions are:

  1. serialize / unserialize - state saving goodness via sql, cookies, processes, flatfile. good stuff.
  2. json_encode / json_decode - instant AJAX fun
  3. get_class - helpful for those weary loose-typing moments
  4. call_user_func_array - powerful when you can work with your code as strings (think dynamic)
  5. method_exists - reflection
  6. func_num_args / func_get_arg - unknown arguments ftw
  7. set_error_handler / set_exception_handler - very good debugging capabilities for a scripting language
Score: 13

a) the manual -- extremely comprehensive, up-to-date 30 and just a huge source for inspiration while 29 problem-solving - stuck? browse/search the 28 manual, it'll come to you

b) arrays - they're plastic, they're 27 associatively indexed, they can be easily 26 nested (!) to make up some wild data structures, and 25 there's a multitude of functions just for 24 array operations alone. Oh, and did I mention 23 treating separate variables as an array 22 of values?

c) eval() and similar constructs (like 21 dynamic variable and function names) which 20 allow for much greater flexibility (and 19 are still relatively safe provided you know 18 what you're doing) - nothing beats a program 17 that basically defines its own process flow 16 (or even specific execution) on the fly

d) most 15 probably the easiest thing to overlook: as 14 almost everything in the ZEND engine is 13 a zVal (which in essence is a collection of 12 pointer references), the ability to return 11 about anything as a function return value

Also, I'd 10 like to point out one great feature, but 9 one which is related more to PHP source 8 than the language (and so - listed separately):

e) the 7 ease of writing C extensions (mostly interfaces for 6 other objects like OpenAL or SDL) - great 5 source code structure and about as many 4 powerfull tools on the 'inside' as there 3 are on the 'outside' - if you ever need 2 to expand the functionality just that little 1 bit further.

Score: 13

Ctype functions are faster than preg_match() for basic character validation.

ctype_alnum() — Check for alphanumeric character(s)
ctype_alpha() — Check 3 for alphabetic character(s)
ctype_cntrl() — Check 2 for control character(s)
ctype_digit() — Check 1 for numeric character(s)

Score: 13

Date functions. I have to handle a lot of time information 2 and date strings all day long, so functions 1 like strftime() and strtotime() are just awesome.

Score: 12

Error suppression via the error control operator, @, should almost 7 never be used. It promotes lazy and non-defensive 6 coding practices by simply ignoring errors, creates 5 debugging nightmares since errors of all 4 types--even fatal ones--will be suppressed, and, in 3 some cases, can cause a hit to performance 2 (especially when suppressing large quantities 1 of errors).

Score: 12

filter_var function. Not a hidden pearl, but pretty 1 new.

Score: 10

Well, I've recently delivered my first GUI 11 application to a paying customer - written 10 in PHP! It gathers data from a barcode reader 9 or from GUI pushbuttons, checkboxes, radio 8 buttons or text fields, stores to SQLite 7 or remote MySQL, launches other Windows 6 apps, sends zipped XML reports as email 5 attachments, encrypts and decrypts stored 4 data and even plays a sound when done.

Did 3 it with miniPHP and Winbinder. Is that hidden enough? I 2 guess not many PHP developers have really 1 tried this out.

Score: 8

Shorthand Boolean Chains


TRUE AND print 'Hello';
FALSE OR print 'World';

// Prints "Hello World";

// Complex example...
User::logged_in() or die('Not allowed');
User::is_admin() AND print 'Admin Area';

Which is really useful if you have PHP files 4 in a web-accessable area. By inserting this 3 little tidbit at the top of each file you 2 can make sure that no-one can access any 1 file but index.php

<?php defined('YOURCONSTANT') or die('Not allowed');

///rest of your code
Score: 8

You can easily add an element to an array.

$my_array = array();
$my_array[] = 'first element';
$my_array[] = 'second element';

Element 1 may be anything: object, array, scalar...

Score: 8

As others have mentioned, the ability to 7 run PHP at the command line level is fantastic. I set PHP scripts as cron 6 jobs for data cleanup and backup purposes 5 all the time. Just start the file with these 4 lines:

// start coding here

Note that the first line may be different 3 depending on where PHP is installed on your 2 system.

From here, it's easy to implement 1 PHP for more complex system-level processes, like daemons.

Score: 7

Built in filters for parsing variables against 4 specific predefined types - as well as covering 3 the basics (int/float etc), extends to covering 2 emails, urls and even if a variable is a 1 valid regular expression.


Score: 6

Typecasting and the ctype_* functions become important to 6 ensure clean data. I have made extensive 5 use of exceptions lately, which has greatly simplified 4 my error handling code.

I wouldn't say the 3 language has lots of killer features. (At 2 least, I don't find much occasion to seek 1 them out.) I like that the language is unobtrusive.

Score: 6

Using array elements or object properties 2 inside strings.

Instead of writing

$newVar = $ar['foo']['bar'];
echo "Array value is $newVar";

$newVar = $obj->foo->bar;
echo "Object value is $newVar";

You can 1 write:

echo "Array value is {$ar['foo']['bar']}";
echo "Object value is {$obj->foo->bar}";
Score: 6

The ReflectionClass class provides information about a 2 given class.

$classInfo = new ReflectionClass ('MyClass');
if ($classInfo->hasMethod($methodName))                                     
  $cm = $classInfo->getMethod($name);                                   
  $methodResult = $cm->invoke(null);

Among other things, useful to 1 check if a method exists and call it.

Score: 5

preg_split(), array_intersect(), and array_intersect_key().


Score: 5

Just about any file type can be included, from .html 6 to .jpeg. Any byte string found inside 5 bound by PHP open tags will be executed. Yes, an 4 image of goat.se can contain all your usual 3 utility functions. I'm guessing the internal 2 behavior of include is to convert the input file 1 to string, and parse for any php code.

Score: 4

specifying implicitly which parameter type 14 a method expects

Actually, this one is partly 13 possible (at least in PHP5) - you can specify 12 the type for array and object parameters 11 for functions and methods, though you are 10 out of luck in case of scalar types.

class Bar
    public function __construct(array $Parameters, Bar $AnotherBar){}

Apart 9 from this one and the magic methods Allain 8 mentioned, I also find the interfaces provided 7 by SPL (Standard PHP library) indispensible 6 - you can implement the necessary methods 5 in your class, for example, I particulary 4 like the ArrayAccess and Iterator interfaces, that 3 allow using an object like an associative 2 array or iterating over it just like any 1 simple array.

Score: 4

I suggest using PHPUnit for unit testing, if 100 you want to have annotations for marking 99 your tests, and data providers, and data 98 driven tests, and so on. Not to mention, it 97 seems to get all the integration love when 96 it comes to things like continuous integration 95 (cruise control, bamboo, hudson, etc...).

PHP 94 5.3, it's a big jump, and it's throughly 93 worth it in terms of language features. It 92 maybe rough around the edges, but this is 91 a startup and they'll be fixed up releases 90 by the time you launch.

As far as magic methods 89 go __invoke() alone is a big deal, but it 88 doesn't have the reciprocal method for it, even 87 then, paired with array_map, array_reduce, and 86 array_filter, and some wrappers you can 85 do some amazing functional programming.

__get, __set, and 84 __call are really handy as well, I used 83 these and some interface/class naming convention 82 trickery to implement traits prior to 5.3, but 81 now you have traits, as well.

Also have a 80 look at the addendum library, written by 79 derik rethans of ezComponents, and XDebug 78 fame, it allows you to do annotations for 77 php 5+. It's not bad, and performance is 76 a non-issue with caching.

For profiling, you 75 can use xdebug + webcachegrind.

The best 74 IDE is probably the free eclipse PDT, if 73 you use type hinting on parameters, and 72 phpdoc comments for parameters and returns 71 it can figure things out from those and 70 provide you code completion. That should 69 give you decent intellisense.

BTW, it's tempting 68 to do all sorts of crazy string concats, or 67 variable variables, or variable method calls, or 66 variable class creation, do this in more 65 than one place, that's not well documented 64 and easy to search via regex, and you're 63 SCREWED. Forget hard to debug, but refactoring 62 is a major pain. This is something people 61 rarely consider php has NO automated refactoring 60 tools, and refactoring large code bases 59 is VERY hard to do in php.

A few things to 58 caution you, even if you smell the slightest 57 bit of possibility that you might have to 56 deal with multi-byte chars, or 'exotic' character 55 encodings, I strongly urge you to wrap up 54 string handling. In fact, introducing a 53 thin layer of indirection which allows you 52 to shim between or act as seams for testing/injectability 51 between your code and built-ins will make 50 your life easier. Not strictly necessary, but 49 unless you have the benefit of foresight, it's 48 hard to tackle internationalization or such 47 large cross-cutting projects.

autoload, learn 46 it and love it. Run away from hard coded 45 require/includes, or worse, their *_once 44 variants, they tie your hands in terms of 43 injection, instead use an autoloader, simplest 42 thing is to jam all your includes in a array, keyed 41 on the class name, and the value is the 40 file path from some root, it's fast. The 39 wicked thing about this is that it makes 38 testing really easy, as you've implemented 37 a class loader, and so you can do some really 36 neat stuff with it.

PHP 5.3 has name spaces 35 now, jump for joy and use them like a mad 34 man. This alone provides an opportunity 33 to create seams (rare) for testing/injections.

Opcode 32 caches, file accesses are slow, to avoid 31 them, use an opcode cache, it's not just 30 the file access, it's all the parsing, really. If 29 you don't have to parse PER request, it 28 makes a BIG difference. Even doing this 27 for a front controller/interceptor will 26 give you a lot of benefits.

Think different, one 25 of the most troubling things for PHP programmers 24 if they come from Java/.Net is that your 23 application server is spread across PHP/Apache, or 22 whatever web server you're using.

Phing/Ant/PHPMaven 21 early on it seems easy just to jam everything 20 in, but build scripts are still useful in 19 php and they have some great support.

I had 18 trouble with method overloading, and still 17 contend with it. I came up with a pattern 16 to alleviate a certain aspect of it. I often 15 had many things that could fulfill a certain 14 parameter, so when you document it @param 13 mixed(int|array|fooObject) if those were 12 the possibilities, I created a static method 11 called Caster::CastTo($param, $toTypeAsString) that 10 would just run through a case matching the 9 type and trying to convert it to a known 8 type. The rest of the method could then 7 assume that one type, or a failure to convert, and 6 work with that. And since I jammed ALL conversions 5 in one class, it stopped mapping of types 4 from being a cross cutting concern, and 3 since these functions can be individually 2 tested, I could test them once, and rely 1 on them everywhere else.

Score: 4

The alternative syntax for control structures

There are a lot of people who don't know 5 this syntax. When I use pure PHP for templating, this 4 syntax offers a nice and clean way to mix 3 simple control structures such as if or foreach with 2 your HTML template code, usually combined 1 with the <?= $myVar ?> short style of printing a variable.

Score: 4

There's lots of gems hidden in the Standard 7 PHP Library. Array access allows you to 6 build an object that works to an array interface 5 but add your own functionality on top.

Also 4 when you create an ArrayAccess object by 3 setting a flag in the constructor you can 2 read and write an object as either an array 1 or an object. Here's an example:

$obj = new ArrayObject(array("name"=>"bob", "email"=>"bob@example.com"),2);
$obj->fullname = "Bob Example";
echo $obj["fullname"];
$obj["fullname"]="Bobby Example";
echo $obj->fullname;
Score: 4

I also like the difference between ' and 5 ".

$foo = 'Bob';
echo 'My name is {$foo}'; // Doesn't swap the variable
echo "My name is {$foo}"; // Swaps the variable

Therefore, if your string doesn't need 4 variable swapping, don't use a ", it's a 3 waste of time. I see lots of people declaring 2 strings with " all the time.

Note: I use 1 { } as it makes my variables stand out more.

Score: 4

I'm partial to the other PHP users out there. It's 1 easy to get answers and direction when necessary.

Score: 3

I have started to switch over to python, and 7 one thing I loved in python is the live 6 interpreter. It wasn't until working on 5 a php project later that I realized php 4 does have this option, it's just not widely 3 known. In a command prompt, type php -a and paste 2 in any php code you want to test, but just 1 remember to start it with <?php

Score: 3

Well, the community is in the first place for me. Whatever 18 can your problem be, you'll always find 17 someone who had it before and almost every 16 time a solution... and sometimes I've seen 15 a completely free share of ideas, ways to 14 approach a single problem.

I'm trying to 13 learn Python now (to grow up as... well.. programmer, can 12 that be?) and the most useful thing of Python 11 is the indentation. I love the PHP indentation, the 10 $ mark for sign the variables, curly braces 9 for loops and cycles, well, those smart 8 things keep my code very easy to understand 7 (even if the one who's wrote the code was 6 little..messy up.. 'spaghetti-code', mh?)

Arrays, in 5 PHP are pretty simple and powerful.

Databases: MySQL, Postrgee, sql; you 4 can use almost every kind of databases.. easily.

Quick: logically 3 depends by how is the code wrote, but usually 2 PHP is pretty fast for small/medium application (as it lose wheel in bigger 1 application).

Score: 3

I think that their proper respect for the 1 GOTO function is key.


Score: 2

How extremely easy is to find PHP related 6 things Examples, Applications, Classes, Documentation, Frameworks, etc...

All 5 over the web, it's the easiest language 4 to learn when going commando(by yourself), and 3 also the one with more value for your time.

After 2 learning PHP might put CMS with joomla, a 1 blog with wordpress, etc....

Score: 2

Let's see...

  1. Ternary operators. They work 10 wonders for processing checkboxes in form 9 results.

    $var = ($_POST['my_checkbox']=='checked') ? TRUE 8 : FALSE;

  2. All of the wonderful string and 7 array processing functions are worth trawling 6 through. strtotime(), strlen(), and strpos() are 5 a few of my favorites.

  3. The SimpleXML class 4 and json_decode() function. Call a REST 3 API or RSS feed with file_get_contents(), parse 2 it effortlessly with one of those tools, and 1 you're done.

Score: 2

The predefined interfaces:


For example implementing 12 ArrayAccess will make your object appear as an array 11 or Iterator will allow it to be used in a foreach 10 statement.

Unfortunately you can't use "object 9 arrays" with the native functions that 8 take arrays as parameters.

I also found it 7 useful to override the __call function which allows 6 you to dynamically create properties and 5 methods for an object.

In my database abstraction 4 I use this to generate functions that are 3 named by the database column names. For 2 example if there is a column 'name' then 1 you can change values in it by using updateByName("foo").

Score: 2

Lambda functions

Example - sort by field in multidimension-array

function sort_by_field($field, & $data) {
    $sort_func = create_function('$a,$b', 'if ($a["' . $field . '"] == $b["' . $field . '"]) {return 0;} 
            return ($a["' . $field . '"] < $b["' . $field . '"]) ? -1 : 1;');

    uasort($data, $sort_func);

Anonymous functions

Anonymous 2 functions lets you define a function to 1 a variable. http://www.php.net/manual/en/functions.anonymous.php

Score: 1


  • The wide aceptance of PHP in WebHosting. Nearly every web-hosting service has PHP support.
  • Simple things can be solve with simple code. No classes or namespaces are strictly required.


  • There is a ton of functions without any naming-convention. It is so hard to remember all these functions to use it effectively.
  • Bad coding habits, all over the web :(


Score: 1

This is great:

//file page_specific_funcs.inc

function doOtherThing(){


class MyClass{


//end file


function doSomething(){

  $var = new MyClass(); 

//end of file.php

"page_specific_funcs.inc" file 3 is only included if doSomething gets called. The declaration 2 of classes, funcs, etc., inside methods 1 works perfectly.

Score: 1

Definitely the magic and overloading methods. Allain 8 cited __get(), __set(), __call() and __toString(), but 7 I also love __wakeup() and __sleep().

This 6 magic methods are called when the object 5 is serialized (sleep) and deserialized (wakeup). This 4 feature ables making things like serializable 3 Database-wrappers, which i am using in an 2 application:

Class Connection {
   private $dsn;
   private $connection;
   public __wakeup() {
      $this->connection = ADONewConnection();

In this way i can "save" connections 1 in $_SESSION, etc.

Score: 1

The json_encode/decode functions in php 1 are pretty useful, though not very hidden.

Score: 1

In PHP5.3 you can place PHAR archives inside 2 PHAR archives! Like WAR/EJB in the java 1 world.

Score: 1

My revelations over the years have been 23 more conceptual than language based.

1: Rendering 22 instead of echoing.

function render_title($title){
     return "<title>$title</title";

so much easier to use 21 the parts repeatably and pass them to templates 20 when you are rendering your output instead 19 of using echos (in which case you'd have 18 to rely on output buffering).

2: functional 17 programming, or at least as close as I can 16 move towards it, functions without side-effects. Rendering, not 15 using globals, keeping your functions to 14 having a local scope, things like that. I 13 thought that object oriented programming 12 was the way to go with php for a while there, but 11 the reduction in overhead and syntax complexity 10 that I experienced from dropping down from 9 object oriented methods to functional programming 8 methods in php makes functional programing 7 the clear choice for me.

3: Templating systems 6 (e.g. smarty). It's taken me a long time 5 to realize that you -need- a templating 4 system inside what is already a template 3 scripting language, but the seperation of 2 logic from display that it gives you is 1 so, so necessary.

Score: 1

Lot already said about this.

Just to add 4 that one thing that looked pretty forgotten, if 3 not hidden, is http://talks.php.net part of the http://www.php.net. It collects 2 lot of useful presentations, some really 1 old, but some new and extremely valuable.

Score: 1

Stackable unit files

// file unit1.php
$this_code='does something.';

// file unit2.php
$this_code='does something else. it could be a PHP class object!';

// file unit3.php
$this_code='does something else. it could be your master include file';

// file main.php

I purposely used include and require_once 10 interchangeably to show what can be done, because 9 they work differently.

There are multiple 8 ways to construct your code or add files 7 into your code. It is even possible to link 6 HTML, AJAX, CSS, JAVASCRIPT, IMAGES and 5 all sorts of files into your code dynamically.

I 4 especially like it, because there are also 3 no requirements of placing the includes/requires 2 at the beginning, middle or end. This allows 1 for more freedom, depending on the use.

Score: 0

Magic method __callStatic.

Really useful to make singletons, like 1 this PDO singleton class

Score: 0

Question about the original post: Why do 10 you need a switch statement in order to 9 overload a method in PHP? Maybe you mean 8 something by the term "overload" that doesn't 7 match what I learned from C++.

As for favorite 6 features of PHP, I like the Exception object. I 5 find that having a standard error container 4 makes it much easier to decouple the presentation 3 logic from the business logic, and the throw/catch 2 syntax makes it much easier to write automated 1 tests for each class in isolation.

Score: 0

Using cURL to set up a test suite to drive a 4 large, complex web form and its back end 3 application. The tests were exhaustive 2 - at least in terms of executing every combination 1 of acceptable inputs.

Score: 0

Another nice feature is copy(). This function 4 makes it possible to get a file from any 3 place(even urls work) and copy it to a local 2 resource. So grabbing files becomes really 1 easy.

More Related questions