即時通訊工作與PHP和MySQL,有時我需要實例化我的PHP類在數據訪問層返回對象,加載列表等......但有時我使用類構造函數和其他人不。可以在php類中創建構造函數doble嗎?
我可以在類中創建doble構造函數嗎?
例如:
class Student {
private $id;
private $name;
private $course;
function __construct() {
}
//get set id and name
function setCourse($course) {
$this->course = $course;
}
function getCourse() {
$this->course = $course;
}
}
class Course {
private $id;
private $description;
function __construct($id) {
this->id = $id;
}
//get set, id, description
}
在我的接入層有時我使用構造函數以不同的方式 例如:
$result = $stmt->fetchAll();
$listStudent = new ArrayObject();
if($result != null) {
foreach($result as $row) {
$student = new Student();
$student->setId($row['id']);
$student->setName($row['name']);
$student->setCourse(new Course($row['idcourse'])); //this works
$listStudent ->append($sol);
}
}
但有時我需要使用構造以另一種方式,例如我的英語很差, 我希望你明白我的
你的英語很好,但我不明白你想達到什麼目的。你想創建一個具有兩個(或更多)構造函數的類嗎? – axiac
構造函數的目的是初始化對象的屬性,以使其可以使用。在'Student'類中發生的空構造函數(+ setter)是僞裝成OOP的程序編程的標誌。將'Student'屬性的初始化放入其構造函數中,並刪除這些setters。 – axiac
嗨,我想要實現的是創建對象與構造函數,並沒有構造函數,沒有原因的錯誤...例如: $ course = new Course(); - >作品 和 $ course = new Course($ id); - >也可以工作 但是因爲我有ir不工作: $ course = new Course(); - >不工作 和 $ course = new Course($ id); - >作品 感謝您的時間 –