在 PHP 中执行多个构造函数的最佳方法

2021-12-30 00:00:00 constructor php multiple-constructors

您不能在 PHP 类中放置两个具有唯一参数签名的 __construct 函数.我想这样做:

You can't put two __construct functions with unique argument signatures in a PHP class. I'd like to do this:

class Student 
{
   protected $id;
   protected $name;
   // etc.

   public function __construct($id){
       $this->id = $id;
      // other members are still uninitialized
   }

   public function __construct($row_from_database){
       $this->id = $row_from_database->id;
       $this->name = $row_from_database->name;
       // etc.
   }
}

在 PHP 中执行此操作的最佳方法是什么?

What is the best way to do this in 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 的学生:

Then if i want a Student where i know the ID:

$student = Student::withID( $id );

或者如果我有一个 db 行数组:

Or if i have an array of the db row:

$student = Student::withRow( $row );

从技术上讲,您不会构建多个构造函数,只是构建静态辅助方法,但您可以通过这种方式避免在构造函数中使用大量意大利面条式代码.

Technically you're not building multiple constructors, just static helper methods, but you get to avoid a lot of spaghetti code in the constructor this way.

相关文章