我最近在PHP中開始學習面向對象,並且我有這個小代碼。 我有這樣的代碼在class.php: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);
我每當我在教師o中使用create()方法時,都希望對數據庫做一些事情(例如插入) bject。
什麼是正確的路要走?
- 我需要在每種方法中創建一個新的mysqli對象嗎?
順便說一句 - 我的代碼的一個小審查將是史詩般的。就像,我很想知道我是否有這個權利。
通行證create方法? – developerwjk 2014-10-29 22:45:24
[核心評論](http://codereview.stackexchange.com/)可能更適合這類問題。 – Shoe 2014-10-29 22:47:10
您的意思是添加$ sql到「創建($ id,$ name,$ phone,$ vehicle)」?因爲這不起作用(警告:對於Teacher :: create()缺少參數5) – user3800799 2014-10-29 22:48:01