PHP-DI annotation not working

700 Views Asked by At

I have installed php-di 4.4 in a new custom project using composer.Im runing a xampp localhost with php 5.6.3 but I set netbeans for php 5.4 on this project. Im new to php-di, I did use annotations in my android projects but cant seem to make it work here. The code is simple, im testing out the injection to see how it works, here is the code:

// composer autoload
require_once __DIR__ . '/vendor/autoload.php';

// injection entry point
$builder = new DI\ContainerBuilder();
$container = $builder->build();

class ClassA
{
    public function methodA()
    {
        echo 'methodA';
    }
}
class ClassB
{
    /**
     * @Inject
     * @var ClassA
     */
    public $param;

    public function methodB()
    {
        $this->param->methodA();
    }
}

$b = new ClassB();
$b->methodB();

this is the error that i get: Call to a member function methodA() on null in D:\Projects\profi\test.php on line 27

It's basic implementation I don't understand why it does not inject.

Thank you in advance.

1

There are 1 best solutions below

1
On BEST ANSWER

PHP-DI cannot magically intercept when you create B (to inject A in B). You have to create B using PHP-DI:

$b = $container->get('ClassB');
$b->methodB();