Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

lievikoff's avatar

Namespaces in PHP and Classes with same names

Hi. Could you please help me understand best practice of naming classes in PHP using namespaces?

Example: I have two classes called the same - Assets but they have different namespaces: Acme\App and Acme\App\Admin.

Code:

  • app/assets.php (supposed to enqueue frontend assets):
namespace Acme\App;

Assets {
    public function __construct() {
        $this->some_functionality();
    }
}
  • app/admin/assets.php (supposed to enqueue backend assets):
namespace Acme\App\Admin;

Assets {
    public function __construct() {
        if ( ! is_admin() ) {
            return;
        }

        $this->some_functionality();
    }
}

Question: The idea of namespaces is get rid of prefixes and group code. But is that not confusing? Should i name the Acme\App\Admin\Assets class with a prefix Admin like Admin_Assets?

PS: Of course i could keep all assets in the same class with a condition where to enqueue them, but it is probably much better idea to split in two files.

0 likes
2 replies
topvillas's avatar

You can name classes what you want and put them in whatever namespace you want but you won't be able to autoload them using composer.

Just stick with the PSR4 conventions and your life will be easier.

1 like
Snapey's avatar
Snapey
Best Answer
Level 122

The namespace ensures you avoid collision so if you need to use new Assets in a class then you can use the namespace to determine the correct one.

If you find it confusing when using the code then you can alias it within the class where it is used

use Acme\App\Admin\Asset as AdminAsset

class myFunkyClass
{

    public function doStuff()
    {

        $asset = new AdminAsset();

2 likes

Please or to participate in this conversation.