我想将连接链接传递给一个类。我尝试这样但无法得到解决方案 这里 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;
}
}
?>
我直接和通过函数分配了类似的东西。但没有成功
答案 0 :(得分:1)
首先,我将通过构造函数
分配连接class clscheckout {
// snip
private $con;
public function __contruct(mysqli $con) {
$this->con = $con;
}
// etc
并使用
实例化它require_once 'dbconnect.php';
$chechout = new clscheckout($con);
然后,请确保在$this->con
方法中使用clscheckout
而不是$con
。这适用于所有类属性。见http://www.php.net/manual/language.oop5.properties.php
您的global $con
脚本中也不需要dbconnect.php
。
答案 1 :(得分:1)
最好的方法是先创建一个mysqli类的实例:
dbconnect.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);
答案 2 :(得分:0)
您是否尝试过此操作(通过引用传递$ conn而不是按值传递)?
function setConn (&$conn) {
$con=$conn;
}