我正在使用php和mysql,有时我需要在数据访问层中实例化我的php类以获取返回对象,加载列表等...但有时我使用类构造函数而其他人则没有。
我可以在类中创建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);
}
}
但有时我需要以另一种方式使用构造函数,例如
$result = $stmt->fetchAll();
$listCourses = new ArrayObject();
if($result != null) {
foreach($result as $row) {
$course = new Course(); //but here not work, becouse Class course receives a id
$course->setId($row['idcourse']);
$course->setDescription($row['description']);
$listCourses->append($sol);
}
}
我的英语非常糟糕, 我希望你理解我
答案 0 :(得分:0)
class Course {
private $id;
private $description;
function __construct($id = 0) {
this->id = $id;
}
// getters and setters for id and description
}
现在,您可以像这样使用它:
$course = new Course(12); // works with argument
或:
$course = new Course(); // works without argument
$course->setId(12);
答案 1 :(得分:0)
class Course {
private $id;
private $description;
public function __construct() {
// allocate your stuff
}
public static function constructWithID( $id ) {
$instance = new self();
//do your stuffs here
return $instance;
}
当你必须传递id时,调用类似Course :: constructWithID(.. id),否则make object(new Course())。