如何在类内部使用mysqli_query


How to use mysqli_query inside of a class

我正在用PHP 5.6.6设计一个网页,试图使用一些OOP思想。当我在文件index.php中包含文件classnews.php时,我会得到错误

Undefined variable: connect in classtin.php

classdb.php:

<?php
class db
{
    public $hostname = "localhost";
    public $user= "root";
    public $pass = "";
    public $db = "test";
    /* public $connect = NULL;
    public $result = NULL;*/
    function __construct()
    {
        $connect = mysqli_connect($this->hostname, $this->user, $this->pass,$this->db);
        mysqli_set_charset($connect,'utf8');
    }
}
?>

classnews.php:

<?php
    include_once('classdb.php');
    class tin extends db
    {
        public function tinmoi()
        {
            $sql= "select * from emp ";
            $result= mysqli_query($connect,$sql);
            return $result;
        }
    }
?>

您需要通过$this引用类成员。例如,与$this->hostname相同。

修改您的代码部分:

class db
{
    public $hostname = "localhost";
    public $user= "root";
    public $pass = "";
    public $db = "test";
    public $connection;
    public function __construct()
    {
        $this->connection = mysqli_connect($this->hostname, $this->user, $this->pass,$this->db);
        mysqli_set_charset($this->connection,'utf8');
    }
}
class tin extends db
{
    public function tinmoi()
    {
        $sql = "select * from emp ";
        return mysqli_query($this->connection, $sql);
    }
}

再次,我强烈建议您学习PHP中OOP的基础知识:http://php.net/manual/en/language.oop5.basic.php