php - 当类启动失败时,我可以返回 null 而不是对象吗?
问题描述
是否可以设计一个类构造函数来销毁对象或在启动失败时将其设置为 null。例如在下面的代码中 - 如果在数据库中找不到用户,那么将对象设置为 Null (A) 可能很有用......还是使用类成员标志$found
(B) 更好?
<?php
class User {
private $name = "";
public $found = true;
function __construct($username) {
if (!db_lookup_user($username)) {
$this = null; // A. This won't work - but can I return null instead of an object?
$this->found = false; // B. The alternative is to set a flag that indicates that the object is valid
} else {
$this->name = $username;
}
}
}
$myUser = new User("Donald Duck);
if (is_null($myUser)) { echo "User doesn't exist"; }
... or ...
if ($myUser->found == false) { echo "User doesn't exist"; }
解决方案
您可以使用工厂模式(https://en.wikipedia.org/wiki/Factory_method_pattern)(或类似的东西)
<?php
class UserFactory {
static function createUser($username) {
if($username == 'something') {
return new User();
} else {
return null;
}
}
}
class User {}
$user1 = UserFactory::createUser('something');
$user2 = UserFactory::createUser('somethingElse');
var_dump($user1,$user2);
输出
object(User)#1 (0) {}
NULL
推荐阅读
- html - 在图像悬停时,覆盖原始图像并显示文本
- javascript - Teamasys skylink-webrtc Web 集成解决音频和视频呼叫控制台问题
- jquery - 将参数传递给按钮单击到另一个按钮单击-Jquery
- javascript - Javascript Randomizer重复所有切片?
- javascript - Vue 的 ref 每次使用时都会执行一次 DOM 查找吗?
- android - 如何检索 CountryCode / ISO?
- java - 在 Java 项目的 intellij idea 中创建工件和执行 jar 文件时出错
- java - Salesforce - Apex 类/触发器不允许 3 个连续字符
- python - 从 .osm 文件中绘制未排序的方式/区域的节点引用
- ios - 替换 App Store 中应用的通配符签名证书和配置文件