Magento 2
Dependency Injection in PHP 8
Free Preview
PHP 8+
<?php
namespace Foo\Bar\Model;

use Psr\Log\LoggerInterface;

class Baz
{
    // Instead of needing to define multiple references to $this->logger,
    // we define the scope right within the constructor.
    public function __construct(
        private LoggerInterface $logger
    ) {
        // $this->logger is already available to us at this point, so we can
        // call object methods immediately, even right in the constructor!
        $this->logger->info('This is much better :)');
    }
}
PHP <=7
<?php
namespace Foo\Bar\Model;

use Psr\Log\LoggerInterface;

class Baz
{
    // The scope needs to be defined outside of the constructor.
    private $logger;

    // We need to reference $logger again when instantiating with DI...
    public function __construct(
        LoggerInterface $logger
    ) {
        // ..and yet again, two more times within the constructor!
        $this->logger = $logger;
    }

    public function execute()
    {
        // $this->logger is also only available from outside the constructor.
        $this->logger->info('This is a lot of typing...');
    }
}
Want to learn more?

Visit M.academy to learn much more about Magento, Laravel, PHP, Javascript, & Docker.

M.academy logo