I want to add this string "declare(strict_types=1);" after <?php when I save or open a file.


If the file already contains declare(strict_types=1); don't do anything.

Maybe there is a plugin or something? Thank you.

2 Answers 2


Something like this should work:

function! AddPHPStrictTypes()
    " Save the cursor position
    let cursor_save = getpos('.')

    " Go to the begining of the file
    call cursor(1, 1)

    " Get the line containing "<?php"
    let phpLine = search('<?php')

    " If the declaration isn't in the buffer and there is one line containing "<?php"
    if search('<?php\ndeclare(strict_types=1);') == 0 && phpLine != 0
        " Add the declaration after the line
        call append(phpLine, "declare(strict_types=1);")

    " Restore cursor position
    call setpos('.', cursor_save)

autocmd! BufReadPost *php call AddPHPStrictTypes()

We declare a function which searches for the declaration. If the declaration is not found it search for the line containing <?php and add the declaration after it.

Then we use an autocommand to execute the function each time you open a new php file.

To understand the function better you may want to read

And to change the autocommand:

  • 1
    use append(), instead of putting, be sure to set the cursor to the beginning of the file before searching and restore the position later Commented Feb 21, 2018 at 10:59
  • 1
    @ChristianBrabandt Thanks for your comment, I updated my answer :)
    – statox
    Commented Feb 21, 2018 at 11:53
  • 1
    Thank you so much for your help, It works perfectly & I learned a lot.
    – whitesiroi
    Commented Feb 22, 2018 at 1:08

I love the accepted solution. But for anyone else who wants to do this quickly, but not always automatically, here is another solution:

iabbrev dst declare(strict_types=1);

With this, in insert mode, move the cursor where you want, then type dst, then hit the space bar, and it will auto-complete it.

If you are working in legacy code environments, it's nice because you can't always add strict types on every file you touch in some cases.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.