PHP实现多个构造函数的最佳方法:
<?php
class Student
{
public function __construct() {
// allocate your stuff
}
public static function withID( $id ) {
$instance = new self();
$instance->loadByID( $id );
return $instance;
}
public static function withRow( array $row ) {
$instance = new self();
$instance->fill( $row );
return $instance;
}
protected function loadByID( $id ) {
// do query
$row = my_awesome_db_access_stuff( $id );
$this->fill( $row );
}
protected function fill( array $row ) {
// fill all properties from array
}
}
?>
然后,如果我想要一个我知道ID的学生:
$student = Student::withID( $id );
或者,如果我有一个db行数组:
$student = Student::withRow( $row );
从技术上讲,你不是构建多个构造函数,只是构造静态辅助方法,但是你可以通过这种方式避免构造函数中的大量意大利面条代码。
继续阅读与本文标签相同的文章
-
Openai研究用仅单个机器手掌就能解决的魔术方块
2026-05-15栏目: 教程
-
韩国移动运营商LG U+选择爱立信为5G无线接入网供应商
2026-05-15栏目: 教程
-
UG编程干货:开启刀具半径补偿的两种方法教学
2026-05-15栏目: 教程
-
RayData数据可视化系列课程第二讲——常见的数据可视化图表类型
2026-05-15栏目: 教程
-
2019年的5大“绿牌”专业,业率和薪酬“双高”,发展潜力大
2026-05-15栏目: 教程
