【发布时间】:2017-11-13 04:38:44
【问题描述】:
我使用 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);
}
}
我的英语很差, 希望你能理解我
【问题讨论】:
-
你的英语很好,但是我不明白你想要达到什么目的。你想创建一个有两个(或更多)构造函数的类吗?
-
构造函数的目的是初始化对象的属性,使其可以使用。
Student类中出现的空构造函数(+ setter)是伪装成 OOP 的过程编程的标志。将Student属性的初始化放到它的构造函数中,去掉setter。 -
嗨,我想要实现的是创建有构造函数和没有构造函数的对象,不会导致错误......例如: $course = new Course(); --> 作品和 $course = new Course($id); --> 也可以,但因为我没有工作:$course = new Course(); --> 不工作并且 $course = new Course($id); --> 感谢您的宝贵时间
-
没有“没有构造函数的对象”这样的东西。具有属性而没有构造函数或具有空构造函数的对象只是一个可以包含任何内容的乏味数据结构。 OOP 是关于(数据的)封装和行为。在您的问题中发布的课程
Student和Course是浪费时间和资源,而不是OOP。您可以使用数组来代替,结果相同(代码更少)。