2

I have looked through the PHP-Fig website for any PSR related to alternative PHP syntax for control structures but failed to find anything about it.

The alternative syntax is this for example:

<?php foreach ($arr as $foo) : ?>
    <h1>block start</h1>
    <?php if ($foo === 'test') : ?>
        <a>Case1</a>
    <?php elseif ($foo === 'test2') : ?>
        <a>Case2</a>
    <?php else : ?>
        <a>CaseElse</a>
    <?php endif; ?>
    <h1>block end</h1>
<?php endforeach; ?>

So is it just not defined and thus ok to use, or is it not compliant since there is no mention about it in the coding style sections?

Theo
  • 2,262
  • 3
  • 23
  • 49
  • 4
    that looks fine to me, though, I've personally shifted towards using twig, keeps the languages a bit more separate, but it's personal preference – treyBake Jan 27 '20 at 11:31
  • 1
    To elaborate what @treyBake said: The prevalence of examples (and consequently, people using) a mix of PHP and HTML is why PHP had attracted some bad rap. Please, separate the concerns with TWIG/PUG/Handlebars/Mustache or whatever templating engine. It will make your code more maintainable. – Eriks Klotins Jan 27 '20 at 11:34

1 Answers1

1

According to Section 5 of PSR-12 (Control Structures):

The body of each structure MUST be enclosed by braces. This standardizes how the structures look and reduces the likelihood of introducing errors as new lines get added to the body.

This means that endif, endwhile, endfor, endforeach, endswitch are not compliant with PSR-12.

It would be helpful if PSR-12 was more explicit about this, as it is easy to overlook or misinterpret this.

Liam
  • 19,819
  • 24
  • 83
  • 123