php / php/php-src

declare statement is not scoped when using curly braces

Open
#9,446 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Bug Category: Engine Status: Needs Triage
Dominant language
C
Stars
40.4k
Forks
8.2k
Avg merge
2d 13h
Merged PRs (30d)
96

Description

Description

When writing tests for phpcs sniff using some useful helpers regarding declare statements, I came up with an unusual behavior of the declare statements, when braces are used.

I was testing out a code that looked like this:

<?php
declare(strict_types=1)
echo 'hi!';

{
// Code.
}

that threw a fatal error because you cannot use curly braces with strict_types directive or alternative control structure syntax (declare: ... enddeclare;)

So I tried to see what will happen if I use a directive that allows the use of curly braces, like encoding. So I tried:

<?php

declare(encoding='ISO-8859-15')
echo 'aäaß' . "\n";

{
echo 'aäaß' . "\n";

}

And I got out:

aÀaÃ
aÀaÃ

I thought I'd get a parse error like when you omit the : when using if with endif; statement. Although, when testing the if statement with the curly braces, like in the example above, I can also see the echoed value before the condition, so I guess that's kinda expected.

What was a buggy behavior was this:

<?php

declare(encoding='ISO-8859-15') {
    echo 'aäaß' . "\n";
}

echo 'aäaß' . "\n";

I expected to see

aÀaÃ
aäaß

But I got (again)

aÀaÃ
aÀaÃ

So it seems that the declare statement, no matter if we are using curly braces, or alternative control structure syntax, will be applied throughout the file, instead of being scoped.

PHP Version

PHP 7.4.26

Operating System

Ubuntu 20.04 (on WSL)

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

The issue does not name a source file or test entry point. Start by reproducing the PHP 7.4.26 examples involving declare(encoding=...) and curly braces, then trace declare handling in the PHP interpreter. Done means the directive is scoped to the braced statement and the reported behavior is covered by a regression test.

Written by the indexing model from the issue text.

Assessment

Tech stack
php
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.