Some very cool features in PHP7

I played around with PHP7 over the weekend and I have to admit it has some very cool things I have wanted PHP to have for a while, and then some. Here are some of them (in no particular order):

  • Performance

    PHP7 will increase the performance of PHP scripts by 50-60%. Nuff said.

  • Anonymous Classes

    I have always been able to do this in Java where I can just define a required object and pass it along.
    Now, you can do the same in PHP (I know that it is a double-edged sword and can leave your code un-organized
    if not used wisely). Here is an example:

    addInsertListener(new Class implements DbInsertObserver {
    	public function log($sql)
    	{
    		// log here 
    	}
    });
    
    
    		

    This can be pretty useful if all you are troubleshooting a production-only issue. Ideally, your testing
    environment will be exactly like your production environment. And, you are able to re-produce every production
    bug in QA but real world is rarely meets ideal standards. We, now, have anonymous classes to help.

  • Scalar type-hinting and Return type hinting

    Ever since PHP introduced type-hinting, I have been using it everywhere I can. It helps with static analysis of code
    and helps prevent bugs (although I love the freedom that comes with PHP not being a statically typed language).

    Note: like previous versions of PHP, PHP7 will not force its user (the PHP developer) to type-hint anything. So, old scripts
    will still work.

    
    
  • Removal of date.timezone warning

    Every time you use a date method, PHP would throw a warning if you didn't have a default timezone set in php.ini
    or in your code (using date_timezone_default_set()). PHP would default to UTC and throw the warning. This warning
    has been removed in PHP7. Good riddance.

  • Null Coalesce Operator

    Also called the isset ternary operator, gives you a more convenient way of ... doing this:

    // Before PHP7
    $someVar = isset($someArray['some_key']) ? $someArray['some_key'] : 'default value';
    
    // In PHP7
    $someVar = $someArray['some_key'] ?? 'default value';
    
    		

There are more cool and useful features I have not mentioned here. You can read about them here: https://wiki.php.net/rfc


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *