声明变量,然后在try / catch中初始化它?

时间:2016-01-14 21:56:39

标签: php

我希望能够在页面内的不同函数中使用$conn,但是因为我在try / catch中初始化它,所以我收到警告说该变量未初始化。如何声明它,然后在try / catch中初始化它?

这不起作用:

global $conn; // or $conn = null; + $this->conn in the next line
try {
    $conn = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);

编辑:
这是一个新尝试:警告说容器未初始化:

$res = $container->db()->query($sql);

新代码:

<?php  
    class Container {

        public function db(){
            $host = "localhost";
            $user = "root";
            $pass = "root";
            $dbname = "test";
            static $conn = null;
            if (!isset($conn)){
                try {
                    $conn = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
                    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                    echo 'connected to db';
                    return $conn;
                } catch(PDOException $e){
                        echo $e->getMessage();
                }
            }

            return $conn;                
        }
    }

    $container = new Container();

    function query($sql){
        $t = microtime(true);
        try {
            $res = $container->db()->query($sql);
            if ($res){
                printf( "%0.2f ms : %s", (microtime(true) - $t)*1000, $sql);
                return;
            }
        } catch(Exception $e){
            echo $e->getMessage();
        }
    }
    query("SELECT * FROM Animal");

1 个答案:

答案 0 :(得分:0)

哦,是的,你已经在上课了。它只需要很少的重新设计。 我建议将query()移到课堂上,但由你决定。

这是一个非常简化的例子;

class Container(){
  protected $conn = null;

  //I would have a constructor, but up to you
  public function __construct(){
    $this->db(); //this will set $this->conn
  }
  public function db(){
    try{
      $this->conn = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
      $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }catch(PDOException $e){
      echo $e->getMessage();
    }
  }

  public function getConn(){
    if( ! $this->conn ){
      $this->db(); //set $this->conn
    }
    return $this->conn;
  }

  public function anyFunctionInYouClass(){
    //you now have access to the connection opbject with $this->conn
    $this->conn->query(); //orwhatever
  }

}

function outsideClass(){
  $db = new db();
  $db->getConn()->query();
}

//OR

//Good if you are using $db in many functions
$db = new db();
function outsideClass($db){
  $db->getConn()->query();
}

这远非一个有效的例子,但希望这个想法很明确。

旁注:不要混用静态变量和实例变量