【问题标题】:Mysql-php Using static or non static connection?mysql-php 使用静态还是非静态连接?
【发布时间】:2016-02-16 02:12:18
【问题描述】:

我是这个主题的新手。我只是想连接我的数据库并获取数据。使用静态连接时,它可以工作,但不能使用非静态连接。正如我所说,我对 Php 了解不多,可能缺少一些简单的东西。 尝试获取非静态时出错 该页面无法显示,因为发生了内部服务器错误。 我的代码

> <?php


class DB_Connect extends mysqli{

  //  protected static $connection;//working
       protected  $connection;   / not working


    function __construct() {

    }


    function __destruct() {


    }
    public function connect() {  
        if(!isset($this->$connection)) {

            $config = parse_ini_file('./configOop.ini'); 
            $this->$connection = new mysqli($config['dbhost'],$config['username'],$config['password'],$config['dbname']);

        }
        else{}
         return $this->$connection;
         /*
        // using this part for static connection object, working
        if(!isset(self::$connection)) {

            $config = parse_ini_file('./configOop.ini'); 
            self::$connection = new mysqli($config['dbhost'],$config['username'],$config['password'],$config['dbname']);

        }
        else{}


        return self::$connection;
        */
    }


    // Closing database connection
    public function close() {
      //  mysql_close();
    }

} 
?>

//

    <?php  include 'db_connectOop.php'; ?>
<?php
 // error_reporting(0);
  $db=new DB_Connect();
   $dbConn=$db->connect();



   if($result =$dbConn->query("Select * from cities")or die($dbConn->error)){

   if($count=$result->num_rows){

      while($row = $result->fetch_object())
      {
       echo $row->idcities;
      }
   }
 }

?>

【问题讨论】:

    标签: php oop mysqli


    【解决方案1】:

    一个小错误:$this-&gt;$connection 应该是 $this-&gt;connection

    PHP 不需要第二个$,因为它已经知道(因为-&gt;)您指的是一个属性。如果您像以前一样添加 $,那么您基本上得到了局部变量 $connection 的值,并将该值用作属性名称。

    【讨论】:

    • ov :)。连接服务器时该怎么办?我应该使用静态、非静态、单例、依赖注入。你有什么建议。我将从远程数据库获取信息到 android 应用程序。
    • 只是我的意见:依赖注入是迄今为止您列出的最佳选择。静态和单例基本上是封装的全局变量。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-17
    • 1970-01-01
    • 2011-02-01
    • 2011-06-11
    • 1970-01-01
    相关资源
    最近更新 更多