10 features in PHP that you really should learn (and use!)

JSONPHPReflection

Please contribute by voting. Thanks!
1

1) Scalar type declarations (PHP7)

PHP is a loosely typed programming language and has as such not provided any means to specify the type of input parameters and return values. PHP7 changed this with the following syntax:

function add(int $x, int $y) : int
{
    return $x + $y;
}

echo add(1, 2);

Valid types are: class/interface name, self, array, callable, bool, float, int and string.

2) ?? - Null Coalesce Operator (PHP7)

The Null coalesce operator is a small but nice addition to PHP7. The ??-operator returns the left side as long as it it exists and is not null, in that case the right side will be returned:

//$a is not defined
$b = NULL;
$c = "abc123";

echo($a ?? $b ?? $c);

//Result: abc123

3) Anonymous classes (PHP7)

Another nice addition to PHP7 is anonymous classes. Sometimes it just does not makes sens to create a named class that bloats the current namespace with it's name. Syntax is pretty straight forward:

echo (new class() {
    public function myMethod() {
      return "Hello!";
    }
})->myMethod();

//Result: Hello!

4) Reflection

Reflection is a really powerful framework to get information about code in run-time. You can reverse-engineer classes, interfaces, functions, methods and extensions in order to construct  mapping-engines, IoC-containers or documentation frameworks among other things.

Here is a simple example that gets all methods from an anonymous class:

$class = new ReflectionClass(new class() {
    public function getText() {
        return "Hello from anonymous class";
    }
});
$methods = $class->getMethods();
var_dump($methods);

More information here:
http://php.net/manual/en/book.reflection.php

5) Short array initializers

I tend to use arrays a lot when programming in PHP as they are both powerful and simple to use. As of PHP version 5.4.x they are even easier to initialize:

$myArray = ["foo", "name" => "bar"];

6) DateTime class

Since version 5.2 PHP ships with the DateTime class as the preferred way to do date and time manipulation and formatting.

More information here:
http://php.net/manual/en/class.datetime.php

7) Lambdas / anonymous functions

Anonymous functions (or lambdas as they sometime are called) are functions which have no specified name. Anonymous functions can be assigned to a variable as shown in the following example:

$sayHi = function($toName) {
    echo("Hi " . $toName);
};

$sayHi("Peter");

More information here:
http://php.net/manual/en/functions.anonymous.php

8) array_map

array_map is a nice little function that will help you do calculations on each element in an array. It is especially nice to use in combination with anonymous functions / lambdas. The array_map function will apply whatever method you supply for each element in the array:

$nameLengths = array_map(function($item) {
    return strlen($item); }, ["Sue", "Peter", "Michael"]);
 
//Result: 3, 5, 7

Note that array_map might be a little bit slower than foreach (especially when used in combination with lambdas) so use with care on very large arrays.

More information here:
http://php.net/manual/en/function.array-map.php

9) json_encode() and json_decode()

I tend to do json serialization and deserialization a lot these days. PHP has great support for this in the json_encode and json_decode functions. Note that json_encode does omit private members:

class car {
    public $make = "Tesla";
    public $model ="Model S";
    private $errorCodes = ['34343', '545344'];
}  
$carAsJson = json_encode(new car());

//Result: {"make":"Tesla","model":"Model S"}

More information here:
http://php.net/manual/en/function.json-encode.php

10) Password hashing and verifying

PHP has great support for hashing and verifying passwords in a secure way via the password_hash and password_verify functions. They are very simple to use so don't reinvent the wheel - use them! Examples can be find in the following articles:

http://www.codeaddiction.net/articles/4/hash-and-verify-passwords-in-php---the-right-way

More...

A few more nice features as a bonus:
* Traits: http://php.net/manual/en/language.oop5.traits.php
* Built-in web server: http://php.net/manual/en/features.commandline.webserver.php
* PDO: http://php.net/manual/en/book.pdo.php

Article created: Jan 12 '16. Edited Jan 17 '16.

Your comment

You need to sign up / log in to comment this article

Author

Created by Robert Bengtsson [126] Jan 12 '16

Share article

Do you know about

git?

Write an article