How to get the constructor class name of the passed in object in PHP?
P粉413307845
P粉413307845 2023-09-11 11:23:19
0
1
602

Suppose I have the following class structure:

class Logger {
    public function __construct(string $channel) {    
        // Logger初始化工作
    }
}

class UsingLogger {
    private Logger $logger;
    
    public function __construct(Logger $logger) { 
        $this->logger = $logger;
    }
}


$logger = new Logger("UsingLogger");
$usingLogger = new UsingLogger($logger);

This code works fine. In this case, the name of the channel is the name of the class. However, I want to use PHP DI (https://php-di.org/doc/php-definitions.html#autowired-objects) to solve this problem. The problem is that it can't resolve the situation because it doesn't know the class name passed to the logger.

Example PhpDI definition

return [
        "SomeLoggerInterface" => autowire(Logger::class)->constructorParameter("channel", // 在这里获取类的名称。在这种情况下,它将是 "UsingLogger")
    ]

Hope this makes it clear. If more context is needed, please let me know.

I have outlined my steps

P粉413307845
P粉413307845

reply all(1)
P粉697408921

I assume you have the DI package installed.

<?php

declare(strict_types=1);

require_once 'vendor/autoload.php';

final class Logger
{
    public function __construct(private readonly string $channel) {}
}

final class UsingLogger {
    public function __construct(private readonly Logger $logger) {}
}

$container = new DI\Container([
    'channel' => 'UsingLogger',
    'Logger' => DI\create()->constructor(DI\get('channel')),
    'UsingLogger' => DI\create()->constructor(DI\get('Logger')),
]);

final class TestClass
{
    public function __construct(UsingLogger $usingLogger) {
        var_dump($usingLogger);
    }
}

new TestClass($container->get('UsingLogger'));

Running this script will produce the following output:

php index.php
path/to/script.php:25:
class UsingLogger#20 (1) {
  private readonly Logger $logger =>
  class Logger#25 (1) {
    private readonly string $channel =>
    string(11) "UsingLogger"
  }
}

Maybe you should also use interfaces. Hope this helps you.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template