BASH one-liner to enable strict typing on all PHP files in a code base

Posted: 2025-07-05 13:02:41 by Alasdair Keyes

Direct Link | RSS feed


Often, if I'm updating an old code base, or have installed a new instance of Laravel, I want to enable PHP's strict typing.

This has to be enabled on each file and can be a bit of a pain so I knocked up a bash one-liner to do this quickly. It works recursively for any *.php file in a given directory.

find codebase/ -name *.php \
    | xargs -i grep -L '^\s*declare\s*(\s*strict_types\s*=\s*1\s*)\s*;.*$' '{}' \
    | xargs -i sed -i 's/\(<\?php\)/\1\n\ndeclare(strict_types=1);/' '{}'

Because blindly running random BASH commands from the internet is a bad idea, a quick break-down of each line....

  1. Search codebase/ directory for every .php file
  2. Check if the file contains the declare(strict_types=1); declaration
  3. If the strict types declaration is not present and the file has the <?php tag, add the strict type declaration after the <?php tag leaving one blank line between the two.

The command is idempotent, so re-running it will not add duplicate strict type declarations into your files.

A word of advice, be selective on which folder you execute it on. If you run it on the root of your code base and have a vendor/ folder, it will update all the PHP files within.


If you found this useful, please feel free to donate via bitcoin to 1NT2ErDzLDBPB8CDLk6j1qUdT6FmxkMmNz

© Alasdair Keyes

IT Consultancy Services

I'm now available for IT consultancy and software development services - Cloudee LTD.



Happy user of Digital Ocean (Affiliate link)


Version:master-173d44c0f5


Validate HTML 5