-5

我想将连接链接传递给一个班级。我尝试以这种方式但无法在此处获得解决方案 dbconnect.php

<?php
global $con;
$db_host="localhost";
    $db_username="root";
    $db_pass="";
    $db_name="xxx";

$con= mysqli_connect("$db_host","$db_username","$db_pass") or die ("could not connect to mysql"); 

mysqli_select_db($con,$db_name) or die ("no database"); 

?>

和我的类 php 文件

<?php
include('dbconnect.php');
$chechout=new clscheckout;


$chechout->con=$con;  // direct assign connection link
$chechout->adult_count=2;
$chechout->child_count=1;
$chechout->child_cwb_count=1;
$chechout->setConn();   // assign throug function
echo $chechout->fnTotel();


class clscheckout{
   public  $pack_id;
   public  $pack_title;
   public  $user_id;
   public  $adult_count;
   public  $child_count;
   public  $child_cwb_count;
   public  $con;


      function setConn ($conn) {
          $con=$conn;
      }

       function fnTotel () {
            $qry='select * from package where pack_id='.$pack_id ;
            $rs=mysqli_query($con,$qry);
            if($rs)
                {
                $row=mysqli_fetch_array($rs);
                $child_wob_price=$row['child_wob_price'];
                $adult_price=$row['adult_price'];
                $child_price=$row['child_price'];
                }

            $adult_total=$adult_price*$adult_count;

            $chidl_total=$child_price*$child_count;
            $child_wob_total=$child_wob_price*$child_cwb_count;

            return $adult_total+$chidl_total+$child_wob_total;

       }

}

?>

我在直接和通过函数中分配了类似的东西。但没有成功

4

3 回答 3

1

首先,我将通过您的构造函数分配连接

class clscheckout {

    // snip

    private $con;

    public function __contruct(mysqli $con) {
        $this->con = $con;
    }

    // etc

并用它实例化它

require_once 'dbconnect.php';
$chechout = new clscheckout($con);

然后,确保$this->conclscheckout方法中使用而不是$con. 这适用于您的所有类属性。见http://www.php.net/manual/language.oop5.properties.php

你也不需要global $con在你的dbconnect.php脚本中。

于 2013-09-26T06:13:50.570 回答
1

最好的方法是首先创建一个 mysqli 类的实例:

数据库连接.php

$mysqli = new mysqli($host, $user, $pass, $db);

if($mysqli->connect_error) {
    die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
}

return $mysqli;

然后

$connection = require_once('dbconnect.php');
$chechout = new clscheckout($connection);

并随心所欲地操纵/传递它。这样你就不会使用讨厌的全局变量

class clscheckout{
   public  $con;


      public function __construct ($conn) {
          $this->con=$conn;
      }

然后将其用作对象

$qry='select * from package where pack_id='.$pack_id ;
$rs=$this->con->query($qry);
于 2013-09-26T06:17:16.150 回答
0

您是否尝试过(通过引用而不是通过值传递 $conn)?

function setConn (&$conn) {
      $con=$conn;
}

有关详细信息,请参阅http://php.net/manual/en/language.references.php

于 2013-09-26T06:14:28.270 回答