【发布时间】:2019-05-18 14:00:45
【问题描述】:
我想声明一个非公共构造函数,因此该类的用户不能直接调用new Message(),而是必须从Message 扩展的抽象类上声明的静态构建器方法实例化对象。
到目前为止,我的代码是:
abstract class SqlDecodable {
public function instanceFromRawSql (array $rawSql) {
$newInstanceToReturn = new static() // problem is here
// .. map the new instance ..
return $newInstance ;
}
}
// for exemple...
class Message extends SqlDecodable {
private $receiverId ;
private $senderId ;
private $text ;
private/protected/public?? function __construct() {
// problem here : this constructor should be usable only by
parent class, not for user of Message
}
static function propertiesToSqlFields() {
return [
"receiverId" => "receiver_id_field_in_db",
"senderId" => "sender_id",
"text" => "text"
]
}
}
这个其实比较复杂,不过我为这个问题简化了系统
当我实现我的方法instanceFromRawSqlArray时,我必须创建一个子类的新实例:$instanceToReturn = new static(),然后一个一个地设置变量。
尽管如此,我不想让 __construct 在我的模型类中不接受任何参数。我不希望 Message 的开发用户能够new Message()。
这个构造函数应该只能被instanceFromRawSqlArray 使用。
问题是,正如我所见,PHP 中没有 C++ 朋友类。我不能让我的 __construct 受保护,因为正如我所见,受保护的方法对孩子来说是可访问的,而不是对父母来说。
您是否有想法在方法 instanceFromRawSqlArray 中映射这个新实例,而不创建任何会破坏我的模型类“封装保护”的构造函数或设置器?
【问题讨论】: