PHP code example of king23 / di

1. Go to this page and download the library: Download king23/di library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

king23 / di example snippets



    
    // get an Instance of the container
    $container = \King23\DI\DependencyContainer();
   
    // register a singleton service
    $container->register(\ExampleInterface::class, function() {
        return new \ExampleImplementation();   
    });
   
    // now that there is a service registered for \ExampleInterface, we can actually use it
    var_dump($container->get(\ExampleInterface::class)); // will dump an instance of \ExampleImplementation
   
    /** 
     * A simple class with a constructor that allows to inject an instance of \ExampleInterface
     */
    class Foobar 
    {
        protected $example;

        public function __construct(\ExampleInterface $example)
        {
            $this->example = $example;
        }
        
        public function dumpExample()
        {
            var_dump($this->example);
        }
    }
    
    $object = $container->get(Foobar::class); // this line would cause $object to be an instance of Foobar
                                                      // having a protected member $example, that holds a reference
                                                      // to the \ExampleImplementation
   
    $object->dumpExample(); // will dump an instance of \ExampleImplementation