V
V
Vadim2020-01-25 20:09:14
PHP
Vadim, 2020-01-25 20:09:14

How to include a class in __construct?

Hello

<?php

interface SessionInterface
{
    public function put($key, $value);

    public function push(string $key, $value);
}

class BaseHandler implements SessionInterface
{
    public function put($key, $value)
    {
        echo 'put';
    }

    public function push(string $key, $value)
    {
        echo 'push';
    }
}

class Session
{
    public function __construct()
    {
        $config = 'BaseHandler';
        
        if ($config == 'BaseHandler') {
            // нужно использовать class BaseHandler
        }
        
        echo 'Session...';
    }
}

$Session = new Session();

How to properly connect BaseHandler ?
Thanks

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Egor Gruzdev, 2020-01-25
@ShVad

class Session
{
    protected $handler;

    public function __construct(SessionInterface $handler)
    {
         $this->handler = $handler;
    }
}

$session = new Session(new BaseHandler);

M
MaLuTkA_UA, 2020-01-26
@MaLuTkA_UA

Why didn't you like inheritance from the BaseHandler class?

<?php

interface SessionInterface
{
    public function put($key, $value);

    public function push(string $key, $value);
}

class BaseHandler implements SessionInterface
{
    public function put($key, $value)
    {
        echo 'put';
    }

    public function push(string $key, $value)
    {
        echo 'push';
    }
}

class Session extends BaseHandler
{
    public function __construct()
    {
        echo 'Session...';
    }
}

$Session = new Session();
// Можно использовать методы class BaseHandler

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question