简体   繁体   English

PHP没有在类上调用构造函数?

[英]PHP not calling constructor on class?

I have a project that I worked on around a year ago. 我有一个大约一年前从事的项目。 I've coded various things in it and it was at a time where I was just starting out on the road to learning dependency injection. 我已经在其中进行了各种编码,而那时我才刚刚开始学习依赖注入。

Long story short, I've forgotten how to pass a parameter to a constructor. 长话短说,我忘记了如何将参数传递给构造函数。 I've tried, although it doesn't seem to do anything. 我已经尝试过了,尽管它似乎没有任何作用。 I've tried looking at the existing code for Dice but I can't work it out. 我尝试查看Dice的现有代码,但无法解决

<?php declare(strict_types = 1);

$dice = new \Dice\Dice;

$configRule = [
    "constructParams" => ["config_directory_here"],
];

$dice->addRule("App\Providers\Configuration", $configRule);

The class in question 有关课程

<?php declare(strict_types = 1);

namespace App\Providers;

class Configuration {
    private $config;

    public function __construct($configDirectory) {
        exit($configDirectory);
        $this->config = array();
        $this->loadConfig($configDirectory);
    }
}

As you can see, in the constructor I have this: 如您所见,在构造函数中,我有以下内容:

exit($configDirectory);

I don't get anything back, it just continues with the code and prints the Twig template, shouldn't it at least just print an empty string even if it didn't get passed? 我什么也没得到,它只是继续执行代码并打印Twig模板,即使它没有被传递,它是否也至少应该打印一个空字符串?

I've not sure if this is a problem with my dice code or my PHP itself. 我不确定我的骰子代码或PHP本身是否有问题。 I have PS4 autoloading so the Configuration class should be included. 我有PS4自动加载功能,因此应该包含Configuration类。

"autoload": {
    "psr-4": {
        "App\\": "src"
    }
}

Can anyone help me here? 有人能帮我一下吗? Thanks! 谢谢! When adding the below code it works as expected, but I need to use a Dependency Injection Container to load the class. 添加以下代码时,它可以按预期工作,但是我需要使用依赖注入容器来加载该类。

$config = new \\App\\Providers\\Config("test");

The constructor is suppose to create an object and cannot return anything but the object it is attempting to create. 构造函数假设要创建一个对象,并且除了它试图创建的对象之外,不能返回任何东西。 You should never create constructors that do any job other then assigning constructor parameters to the object properties. 除了将构造函数参数分配给对象属性之外,您永远不要创建执行任何工作的构造函数。

Full disclosure: I'm the author of Dice. 完全公开:我是Dice的作者。

The reason this isn't working is because Dice never prematurely creates an object. 之所以不起作用,是因为Dice从未过早创建对象。 The Configuration object won't be created until you request an instance from the container: 在您向容器请求实例之前,不会创建Configuration对象:

$configuration = $dice->create("App\Providers\Configuration");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM