Php 抽象类中的多个构造函数
我有一个抽象类(为了演示而简化): 我想添加第二个构造函数,在其中不仅传递标题,还传递id,但是PHP似乎没有方法重载。在网上搜索时,我发现他们建议在哪里创建一个静态方法,该方法将创建并返回同一对象的实例,并充当替代构造函数。大概是这样的:Php 抽象类中的多个构造函数,php,constructor,abstract-class,Php,Constructor,Abstract Class,我有一个抽象类(为了演示而简化): 我想添加第二个构造函数,在其中不仅传递标题,还传递id,但是PHP似乎没有方法重载。在网上搜索时,我发现他们建议在哪里创建一个静态方法,该方法将创建并返回同一对象的实例,并充当替代构造函数。大概是这样的: static function create($id, $title) { $instance = new self($title); $this->id = $id; return $instance; } 这在常规类中很好
static function create($id, $title) {
$instance = new self($title);
$this->id = $id;
return $instance;
}
这在常规类中很好,但在上面的抽象类中不起作用。例如,在执行类似以下操作时:$myclass=myclass::create(“id”、“title”)代码>,我收到错误消息:
异常:无法实例化抽象类MiClase
这发生在$instance=newself($title)行中代码>,这是有意义的,因为它试图实例化自己的抽象类,这是不允许的
在PHP中是否可以为抽象类使用其他构造函数?这里有一个小方法:
<?php
abstract class MyClass {
protected $id = "";
protected $title = "";
function __construct($title) {
$this->id = strtolower($title);
$this->title = $title;
}
static function createWithTitle($title) {
$instance = new static($title);
return $instance;
}
static function createWithIdAndTitle($id, $title) {
$instance = new static($title);
$instance->id = $id;
return $instance;
}
abstract function render();
}
class Concrete extends MyClass {
function render() {
var_dump('id=' . $this->id, 'title=' . $this->title);
}
}
Concrete::createWithTitle('Title')->render();
Concrete::createWithIdAndTitle(1, 'Title')->render();
新静态
<代码>函数uu构造($title,$id=null)
?@tkausl对于这个简单的示例是有效的,但是对于更大的示例和不同的参数组合,它将如何扩展?对于具有大量可选值的对象,您通常会使用builder@tkausl很好。我尝试了$instance=newstatic($title)
我得到了同样的错误让我检查一下本地运行的PHP版本。它成功了。我做错了什么,这就是为什么最初失败的原因。谢谢你的推荐。
<?php
abstract class MyClass {
protected $id = "";
protected $title = "";
function __construct($title) {
$this->id = strtolower($title);
$this->title = $title;
}
static function createWithTitle($title) {
$instance = new static($title);
return $instance;
}
static function createWithIdAndTitle($id, $title) {
$instance = new static($title);
$instance->id = $id;
return $instance;
}
abstract function render();
}
class Concrete extends MyClass {
function render() {
var_dump('id=' . $this->id, 'title=' . $this->title);
}
}
Concrete::createWithTitle('Title')->render();
Concrete::createWithIdAndTitle(1, 'Title')->render();
<?php
abstract class MyClass
{
protected $id = '';
protected $title = '';
public function __construct(...$array)
{
switch (count($array))
{
case 2: $this->title = $array[1];
case 1: $this->id = $array[0]; break;
}
}
}