duansha6410 2017-04-18 13:39
浏览 22
已采纳

类连接器中PDO的实例

I'm working on a project today and i've been working for a while now and i don't see what i do wrong here. Can someone give me the right example.

Thnx a lot!

Connector:

class Repository
{
private $connector;

public function __construct(Config $connector)
{
    $this->connector = $connector;
}

public function events()
{
    $query = 'SELECT * FROM digi_gz_parties';
    $dbh_query = $this->connector->getDatabase()->prepare($query);
    $dbh_query->execute();
    $dbh_querys = $dbh_query->fetchAll();

    return $dbh_querys;
}
}

Getter:

class REST
{
public function getEvents()
{
    require 'logic/Repository.php';

    $event = new Repository();
    $events = $event->events();

    return $events;
}
}

Error: Argument 1 passed to Repository::__construct() must be an instance of Config.

I know i need to give a paramater to the repository but i don't want it, i want only to call the repository without give some paramter.

Thanks a lot!

展开全部

  • 写回答

1条回答 默认 最新

  • dsgw8802 2017-04-18 14:22
    关注

    You can change your Repository::__construct() to have a default $connector to null:

    public function __construct(Config $connector = null)
    {
        $this->connector = $connector;
    }
    

    That way, if you instanciate your object without any parameter, like you do here, it will default to null. The only downside of that is that, now, you have to be extra careful when using $this->connector inside your Repository class and remember it could be null.

    For exemple, here, the second line of your events() method is not going to work, because you lack the proper configuration to connect to your database.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部