PHP Tip: The identity function I()

Here’s a tip I picked up from another PHP programmer. It’s called the identity function, and it simply returns its argument:

function I($subject) {
    return $subject;

Now what so great about that, you ask? One cool thing is that it allows you to instantiate an object and call a method on it, in a single statement:

I(new Foo())->bar();

I know – there’s a built-in way to do this in Java and other languages. Not so in PHP.

Another thing that you often want to do is to call a function that returns an array, then access the nth element of the returned array: $first = $foo->getItems()[0]. Again, in PHP, this is not something that you can do with a single statement. But if we expand our definition of the I() function, we can do it with:

$first = I($foo->getItems(), 0);

Here is the expanded definition of the identity function:

 * The identity function - returns the argument. This is useful for instantiating
 * an object and using it on the same line: I(new Foo())->bar().
 * You can also use it to access array values on the same line: I($user->getLikes(), 0).
 * @param $subject mixed  the object, which will be returned
 * @param $key string  the key whose value to return
 * @return mixed  $subject if no key is specified; otherwise, $subject[$key]
function I($subject, $key = null) {
    if ($key !== null) {
        if ($subject === null) {
            return null;
        if (!is_array($subject)) {
            throw new Exception('Subject is not an array: ' . var_export($subject, true));
        return $subject[$key];
    return $subject;

Using the ub PHP benchmarking tool, you can see that there is a bit of overhead when using the I() function. So this isn’t something that you would want to use in a tight loop:

$ ub not-using-i.php
     not-using-i: mean=0.002162 median=0.002000 min=0.001000 max=0.041000 stdev=0.001435
$ ub using-i.php
         using-i: mean=0.002565 median=0.002000 min=0.002000 max=0.041000 stdev=0.001643

Hopefully the identity function saves you a few keystrokes.

What other little utility functions have you found useful?

Leave a Reply

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