John Davidson

php - Class property gets null as a value

0 comments
Message:


I have two classes:


DI


namespace engine\DI;

class DI
{
/**
* @var array
*/
private $container = [];

/**
* @param $key
* @param $value
* @return $this
*/
public function set($key, $value)
{
$this->container[$key] = $value;

return $this;
}

/**
* @param $key
* @return mixed
*/
public function get($key)
{
return $this->has($key);
}

public function has($key)
{
return $this->container[$key] ?? null;
}
}


and Cms


namespace engine;

use engine\DI\DI;

class Cms
{
/**
* @var DI
*/
private $di;
public $router;

/**
* @param $di
*/

public function __construct($di)
{
$this->di = $di;
$this->router = $this->di->get('router');
}

/**
* @return void
*/
public function run()
{
//$this->router->add('home', '/', 'HomeController:index');
print_r($this->router);
}
}

As you can see in Cms, I put a $router's value in constructor and for some reason it remains null. The interesting part is when I print_r($this->di->get('router')) it works just fine and returns proper value. Even more, when I call method by this value directly (like $this->di->get('router')->add();) it also works wonders, so the value itself is clearly not null. What could be the reason of this?


Here are two additional files where the value comes from:


Provider:


namespace engine\service\router;

use engine\service\AbstractProvider;
use engine\core\router\Router;

class Provider extends AbstractProvider
{
public string $service_name = 'router';

/**
* @inheritDoc
*/
function init()
{
$router = new Router('cms/');
$this->di->set($this->service_name, $router);
}

Bootstrap:


use engine\Cms;
use engine\DI\DI;

try {
$di = new DI();
$cms = new Cms($di);

$services = require 'config/services.php'; //stores an array with providers

foreach ($services as $key => $service) {
$provider = new $service($di);
$provider->init();
}

$cms->run();
} catch (\ErrorException $e) {
echo $e->getMessage();
}


My Answer:
> container[$key] = $value;
return $this;
}

/**
* @param $key
* @return mixed|null
*/
public function get($key)
{
return $this->container[$key] ?? null;
}
}

namespace engine;

use DI;

class Engine
{
private $di;

public function __construct()
{
$this->di = new DI();
}

public function setDI(DI $di)
{
$this->di = $di;
}

public function getDI()
{
return $this->di;
}
}

$engine = new engine\Engine();
$di = $engine->getDI();
$di->set('key', 'value');
echo $di->get('key'); // Output: value
echo $di->get('non_existent_key'); // Output: null

Rate this post

3 of 5 based on 3154 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us