In PHP, autowiring refers to a technique for automatically resolving dependencies when instantiating classes. To implement autowiring in PHP, you can use a dependency injection container, such as PHP-DI package, which provides autowiring out of the box.



Step 1. Install PHP-DI via composer:

composer require php-di/php-di

Step 2. Create a container instance and configure it to use autowiring:

use DI\ContainerBuilder;

$containerBuilder = new ContainerBuilder();
$container = $containerBuilder->build();

Step 3. Define your class and its dependencies:

class Foo {
  public function __construct(Bar $bar) {
    // ...

class Bar {
  // ...

Step 4. Resolve the class using the container:

$foo = $container->get(Foo::class);

The container will automatically instantiate the Bar dependency and pass it to the constructor of Foo.

Autowiring can be limited to a specific namespace or package by using the useAnnotations(false) method of the container builder and annotating the classes with @Inject or @Autowired annotations. Additionally, it's important to note that autowiring can only work with classes that have type-hinted dependencies.

If you want to implement autowiring without any package: How to implement autowiring in php using reflexion class