即时通讯工作与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); - >作品 感谢您的时间 –