将$ con转移到类中的方法上,我必须更改什么?
它应该是“ public”之类的。
class MyClass {
public function __construct()
{
$con=mysqli_connect("localhost", "dbu...", "pw") or die("Error");
mysqli_select_db($con, "db100...") or die("Error");
}
public function doSomething()
{
mysqli_query($con, "");
}
}
谢谢!
PS:我不要$ this-> db-> query()或其他东西:)
答案 0 :(得分:2)
如果要坚持使用mysqli的过程版本,则在面向对象的类中,仍然需要使用$this
,但要有所不同:
class MyClass {
private $con;
public function __construct()
{
$this->con = mysqli_connect("localhost", "dbu...", "pw") or die("Error");
mysqli_select_db($this->con, "db100...") or die("Error");
}
public function doSomething()
{
mysqli_query($this->con, "");
}
}
但是理想情况下,如果您坚持使用对象表示法,则应该一直使用object oriented:
class MyClass {
private $con;
public function __construct()
{
$this->con = new mysqli("localhost", "dbu...", "pw") or die("Error");
$this->con->select_db("db100...") or die("Error");
}
public function doSomething()
{
$this->con->query("");
}
}
答案 1 :(得分:0)
您可以这样做:
class MyClass {
public $con
public function __construct()
{
$this->con=mysqli_connect("localhost", "dbu...", "pw") or die("Error");
mysqli_select_db($this->con, "db100...") or die("Error");
}
public function doSomething()
{
mysqli_query($this->con, "");
}
}
...或这样:
global $con;
class MyClass {
public function __construct()
{
global $con;
$con=mysqli_connect("localhost", "dbu...", "pw") or die("Error");
mysqli_select_db($con, "db100...") or die("Error");
}
public function doSomething()
{
global $con;
mysqli_query($con, "");
}
}
建议使用第一个选项,因为第二个选项可能导致名称空间冲突