PHP面向对象 - 什么是正确的方法?

时间:2014-10-29 22:38:39

标签: php oop object mysqli

我最近开始在PHP中学习面向对象,我有这个小代码。 我在class.php中有这段代码:

## Teacher
class Teacher
{
    public $_id;
    public $_name;
    public $_phone;

    public function create($id, $name, $phone) {
        $this->_id = $id;
        $this->_name = $name;
        $this->_phone = $phone;
    }
}

## Lesson
class Lesson
{
    public $_teacher;
    public $_student;
    public $_price;
    public $_date;

    public function create($teacher,$student,$price,$date)
    {
        $this->_teacher = $teacher;
        $this->_student = $student;
        $this->_price = $price;
        $this->_date = $date;
    }
}


mysql.php:

## MySQL Database Connection

$host = "localhost";
$username = "root";
$password = "";
$dbname = "foo";

// Create connection
$conn = new mysqli($host, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} else {
    echo "Connected successfully";
}

// Create database
$sql = "CREATE DATABASE $dbname";

// sql to create table
$sql = "CREATE TABLE teachers (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
phone VARCHAR(50)
)";

$conn->query($sql);

我在index.php中有这个:

include_once('mysql.php');
include_once('class.php');

## PHP Code
$teacher1 = new Teacher();
$teacher1->create(324,"Ben","054","Audi TT");
var_dump($teacher1);

## PHP Code
$lesson1 = new Lesson();
$lesson1->create($teacher1->_id,date("D d/m/Y H:i"),240,2);
var_dump($lesson1);

每当我在教师对象中使用create()方法时,我想对数据库(例如插入)做一些事情。

什么是正确的方法?

- 我是否需要在每种方法中创建一个新的mysqli对象?

顺便说一下 - 对我的代码进行一次小小的评论将是史诗般的。就像,我很想知道我是否做对了。

1 个答案:

答案 0 :(得分:2)

你可以这样做:

    private $connections = array();

    public function newConnection( $host, $user, $password, $database )
        {
            $this->connections[] = new mysqli( $host, $user, $password, $database );
            $connection_id = count( $this->connections )-1;
            if( mysqli_connect_errno() )
            {
                trigger_error('Error connecting to host. '.$this->connections[$connection_id]->error, E_USER_ERROR);
            }   


            return $connection_id;
        }

     public function closeConnection()
        {
            $this->connections[$this->activeConnection]->close();
        }

        public function insertRecords( $table, $data )
            {
                // setup some variables for fields and values
                $fields  = "";
                $values = "";

                // populate them
                foreach ($data as $f => $v)
                {

                    $fields  .= "`$f`,";
                    $values .= ( is_numeric( $v ) && ( intval( $v ) == $v ) ) ? $v."," : "'$v',";

                }

                // remove our trailing ,
                $fields = substr($fields, 0, -1);
                // remove our trailing ,
                $values = substr($values, 0, -1);

                $insert = "INSERT INTO $table ({$fields}) VALUES({$values})";
                //echo $insert;
                $this->executeQuery( $insert );
            }

public function executeQuery( $queryStr )
    {
        if( !$result = $this->connections[$this->activeConnection]->query( $queryStr ) )
        {
            trigger_error('Error executing query: ' . $queryStr .' - '.$this->connections[$this->activeConnection]->error, E_USER_ERROR);
        }
        else
        {
            $this->last = $result;
        }

    }