【问题标题】:OOP PHP with PDO Connection including different page class带有 PDO 连接的 OOP PHP,包括不同的页面类
【发布时间】:2015-03-10 21:21:12
【问题描述】:

class/dbConnect.php 页面

class dbConnect {
    /*
     * initiate mysql database host,username,password,database name
     */

    private $host;
    private $dbName;
    private $uname;
    private $upass;
    private $con;

    public function __construct($host, $database, $userName, $password) {
        $this->host = $host;
        $this->dbName = $database;
        $this->uname = $userName;
        $this->upass = $password;
        $this->connectDB();
    }

    public function connectDB() {
        /*
         * @var $dsn mean data source name for pdo connection
         */
        $dsn = "mysql:host=" . $this->host . ";dbName=" . $this->dbName;
        try {
            $this->con = new PDO($dsn, $this->uname, $this->upass);            
        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }

}

class/sampleView.php

/*
 * include dbConnect class for this SampleView Class Page
 */
require_once './dbConnect.php';



class sampleViews extends dbConnect{

     function viewUsers(){
         /*
          * dbConncect Class Connection variable access
          */
         $connection = $this->con;

     }
}

这样对吗???我无法使用带有 sampleView 类的 $this-> 方法访问 dbConnect 类 $con 变量

并且可以通过这种方式完成不同的位置类扩展包括页面..帮助Plezzzz

【问题讨论】:

  • 将属性从 private 更改为 protected

标签: php class oop pdo extends


【解决方案1】:

即使扩展父类,您也无法访问private 变量。你需要改成protected:

protected $con;

您还需要构造父类,否则它永远不会实例化父(扩展)类。

function __construct() {
    parent::__construct($host, $username, $password, $db);
}

以上内容将在您的 class SimpleViews extends dbConnect {.... 类中

【讨论】:

  • 你,比我快2秒。
  • @RichardChristensen 哈哈花了我一段时间来格式化代码:P
  • 这里的一个建议是将DbConnect 对象注入到您的视图类中,以消除对parent::__construct(); 的需要
  • @RichardChristensen 我会走同样的路!!我会把它扔掉,只是在回答 OP 的问题范围!
  • 没问题,OOP 设计是我的癖好。
【解决方案2】:

dbConnect 页面

改变了

protected $host;
protected $dbName;
protected $uname;
protected $upass;
protected $con;

和 SampleView 页面

public function __construct() {
    parent::__construct('localhostr', 'test', 'root', '');
}

function chkConnection() {
    /*
     * dbConncect Class Connection variable access
     */
    $dbcon = $this->con;
    if ($dbcon) {
        echo "successfully Connect database";
    } else {
        echo "sorry Could not be connect databsae";
    }
}

有人会更正我的代码吗?

【讨论】:

  • 如果达伦的回答修复了你的代码,你应该接受他的,而不是发布你自己的。访问 meta.stackexchange.com/questions/5234/… 看看那个,然后回到 Darren 的答案,并以与所示相同的方式勾选复选标记。
  • 除了@Fred 所说的之外,您不希望您的host/username/password/db 在课堂外被访问。所以他们应该留下private
猜你喜欢
  • 2017-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-06
  • 1970-01-01
  • 2016-08-10
  • 1970-01-01
相关资源
最近更新 更多