0

For a project assigned to me, I have to stick to following the PSR coding standard for PHP. Now, I am having a hard time understanding one thing.

Is the following PSR-1 and PSR-12 compliant?

<?php

// A.php
abstract class A
{}
<?php

// B.php (in the same directory as A.php)

include 'A.php';
 
class B extends A
{}

In B.php, I am directly including the file A.php. Is this alright? Or does the standard require us to use the use keyword instead, and to leave the rest of the job to PHP's autoloading mechanism, as shown below:

<?php

// A.php

namespace Classes\A;

abstract class A
{}
<?php

// B.php (in the same directory as A.php)

namespace Classes\B;

use Classes\A;
 
class B extends \Classes\A
{}

The problem is that the specification does not state it in clear-cut words that we MUST use classes and namespaces instead of classes and includes (or requires, for that matter). That's why I am confused as to what to do here.

coderboy
  • 1,710
  • 1
  • 6
  • 16
  • When you want to use an (composer) autloader you should go with namespaces. It is not the PHP standard itself, it is used by the composer autoloader to make it clear where the files are located. Think of it like a virtual directory. – Markus Zeller Apr 03 '23 at 11:18
  • @MarkusZeller What about PSR? Does it explicitly require us to use namespaces? Because in the standard, nowhere can I find a class definition with an include preceding it (referring to a parent class); all I see is namespaces. – coderboy Apr 03 '23 at 11:28
  • Not if you do not want to use PSR-Autoloading. – Markus Zeller Apr 03 '23 at 14:19
  • 1
    @MarkusZeller So you mean that namespaces are only required if we want to leverage PSR autoloading, right? – coderboy Apr 03 '23 at 14:35
  • And to avoid name collisions. – Markus Zeller Apr 03 '23 at 15:43
  • The best way to answer this question is to have a linter. For example, you can run `phpcs` with the `PSR12` rule. Neither PSR-12 nor Composer require you to use namespaces, they just provide guidance when you do. – Álvaro González Apr 04 '23 at 09:29

0 Answers0