Emulating the Javascript With Statement in PHP

Written by Ben Wendt

Javascript has a with statement that you probably shouldn’t use. I’ve never seen it used non-jokingly in JavaScript in the past decade or so, other than the occasional clever hack. Visual Basic also has a with statement, and I did see it used a fair bit in that realm, back in the day. In my experience it’s not something that developers are clamoring for.

The main advantage of using with is not having to retype the name of the object you are working with repeatedly in a block of code. The drawback is that this harms readability; an assortment of new variables are presented in the block, and the scope has metaphorically changed gears. A big part of writing readable code is maintaining a good flow and preventing context switches. Because of this, with use is rare.

However, suppose you did want to implement some PHP code where you didn’t want repeated array or object references and you didn’t want to pollute your scope with a call to extract. You could use the following abomination:

call_user_func(function () use ($withVariable) {
    if (is_object($withVariable)) {
        $withVariable= get_object_vars($withVariable);
    }
    extract($withVariable);
    // do stuff.
});

The cumbersome use keyword and its white-list approach to close scope make this a difficult and cumbersome block of code. PHP doesn’t allow immediate execution of anonymous functions directly, so we have to pass the function to call_user_func. In other languages, with will bring variables from the outer scope into the with scope, but that will not happen here unless you add the desired variables into to use arguments.

In conclusion, with is a misfeature and attempting to implement it in PHP is neither very fruitful or elegant.