PHP-使用名称空间创建PDO连接

我有一个项目文件夹名称实用程序。目录列表是:


- utilities

    - tli

        - database

            Connection.php

    index.php

Connection.php是PDOConnection。代码是:


<?php


namespace app\tli\database;


use PDO;

use PDOException;


Class Connection

{

    private $server = "mysql:host=localhost;dbname=ytsurumaru_hanwa_coil_v.2";

    private $user = "root";

    private $pass = "";

    private $options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,);

    protected $con;


    public function openConnection()

    {

        try {

            $this->con = new PDO($this->server, $this->user, $this->pass, $this->options);

            return $this->con;

        } catch (PDOException $e) {

            return "There is some problem in connection: " . $e->getMessage();

        }

    }


    public function closeConnection()

    {

        $this->con = null;

    }

}

更新的来源


现在,我需要index.php中的这个Connection实例


<?php


namespace app;


use app\tli\database\Connection;

use PDOException as PDOEx;


require('tli/database/Connection.php');


try {

    $connection = new Connection(); // not found

    $connection->openConnection();

} catch (PDOEx $e) {

    echo $e->getMessage();

}

当我运行它时


D:\wamp64\www\utilities\tli>php index.php


Warning: require(tli/database/Connection.php): failed to open stream: No such file or directory in D:\wamp64\www\utilities\tli\index.php on line 8


Fatal error: require(): Failed opening required 'tli/database/Connection.php' (include_path='.;C:\php\pear') in D:\wamp64\www\utilities\tli\index.php on line 8

如何解决这个,我的名字有问题吗?


蝴蝶不菲
浏览 184回答 2
2回答

摇曳的蔷薇

这还不足以访问您的数据库连接吗?require 'tli/database/Connection.php';然后,由于您位于不同的名称空间并且没有别名,因此在“ try catch块”中,您应该代替:$connection = new Connection(); // not found做类似的事情:$connection = new \tli\database\Connection();确保正确设置路径。或者您可以使用其他名称作为别名,如下所示:namespace app;require 'tli/database/Connection.php';use tli\database\Connection as MyConnection;$connection = new MyConnection();

收到一只叮咚

您需要使用以下之一:include('tli/database/Connection.php')include_once('tli/database/Connection.php')require('tli/database/Connection.php')&nbsp;require_once('tli/database/Connection.php')或者,如果您需要更多自动化功能,请使用autoloader。您可能需要查看此SO问题以及所有链接的内容。
打开App,查看更多内容
随时随地看视频慕课网APP