可捕获的致命错误:参数1通过

时间:2014-12-23 14:05:58

标签: php oop composer-php

我写这段代码:

的index.php:

(我的索引)

<?php


namespace com;


$loader = require __DIR__ . '/../vendor/autoload.php';
$loader->add(__NAMESPACE__, __DIR__ . '/../../');
$loader->register();

$config = require __DIR__ . "/../config/mainConfig.php";
new framework\com($config);

框架\ COM:

(我的框架主类。  这个类得到配置)

<?php


namespace com\framework;


use com\framework\DTO\IConfig;

class com {
    /**
     * @var IConfig
     */
    private $config;

    /**
     * @param IConfig $config
     */
    public function __construct(IConfig $config)
    {

        $this->config = $config;
    }
}

COM \框架\ DTO \ IConfig:

(日期转移对象)

<?php


namespace com\framework\DTO;


class IConfig {
    /** @var  string  */
    public $projectName;

    /** @var  string  */
    public $projectDescription;

    /** @var  string  */
    public $projectAuthor;

    /** @var array  */
    public $sqlConnectionVariables = array("user", "pass", "options", "connectionString");
}

配置/ mainConfig.php:

(我的主要配置)

<?php


namespace com\config;


class mainConfig {
    /** @var string  */
    public $projectName = "example";

    /** @var string  */
    public $projectDescription = "example";

    /** @var string  */
    public $projectAuthor = "example";

    /** @var array  */
    public $sqlConnectionVariables = [
        "user" => "root",
        "pass" => "",
        "options" => [
            \PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'",
            \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION
        ],
        "connectionString" => "mysql:host=localhost;dbname=example;charset=utf8"
    ];
}

错误:

Catchable fatal error: Argument 1 passed to com\framework\com::__construct() must be an instance of com\framework\DTO\IConfig, integer given, called in C:\wamp\www\com\web\index.php on line 12 and defined in C:\wamp\www\com\framework\com.php on line 18

我该如何解决这个问题? 我需要发送&#34; mainConfig.php&#34;到&#34; com&#34;上课了,它没有用。

2 个答案:

答案 0 :(得分:0)

这是因为如果成功,require的返回值为1

一种可能的修复方式如下:

require __DIR__ . "/../config/mainConfig.php";
$config = new config\mainConfig();
new framework\com($config);

同时使配置扩展类型提示界面(如评论中sjagr所述):

class mainConfig extends com\framework\DTO\IConfig

然后看看还有什么失败。

答案 1 :(得分:0)

你需要这样做:

namespace com\config;

class mainConfig extends \com\framework\DTO\IConfig {
    /** @var string  */
    public $projectName = "example";

    /** @var string  */
    public $projectDescription = "example";

    /** @var string  */
    public $projectAuthor = "example";

    /** @var array  */
    public $sqlConnectionVariables = [
        "user" => "root",
        "pass" => "",
        "options" => [
            \PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'",
            \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION
        ],
        "connectionString" => "mysql:host=localhost;dbname=example;charset=utf8"
    ];
}

return new mainConfig();

但我建议你下次使用真实界面(和单身人士)。