为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
繁星coding 2019-10-23 13:06:54
您不能在PHP类中放置两个具有唯一参数签名的__construct函数。我想这样做: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做到这一点的最佳方法是什么?
查看完整描述

3 回答

?
阿波罗的战车

TA贡献1862条经验 获得超6个赞

Kris的解决方案确实很棒,但我发现工厂和流利的风格更好地融合在一起:


<?php


class Student

{


    protected $firstName;

    protected $lastName;

    // etc.


    /**

     * Constructor

     */

    public function __construct() {

        // allocate your stuff

    }


    /**

     * Static constructor / factory

     */

    public static function create() {

        $instance = new self();

        return $instance;

    }


    /**

     * FirstName setter - fluent style

     */

    public function setFirstName( $firstName) {

        $this->firstName = $firstName;

        return $this;

    }


    /**

     * LastName setter - fluent style

     */

    public function setLastName( $lastName) {

        $this->lastName = $lastName;

        return $this;

    }


}


// create instance

$student= Student::create()->setFirstName("John")->setLastName("Doe");


// see result

var_dump($student);

?>


查看完整回答
1 反对 回复 2019-10-23
?
噜噜哒

TA贡献1784条经验 获得超7个赞

我可能会做这样的事情:


<?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 );

或者,如果我有数据库行的数组:


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

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


查看完整回答
反对 回复 2019-10-23
?
四季花海

TA贡献1811条经验 获得超5个赞

PHP是一种动态语言,因此您不能重载方法。您必须像这样检查参数的类型:


class Student 

{

   protected $id;

   protected $name;

   // etc.


   public function __construct($idOrRow){

    if(is_int($idOrRow))

    {

        $this->id = $idOrRow;

        // other members are still uninitialized

    }

    else if(is_array($idOrRow))

    {

       $this->id = $idOrRow->id;

       $this->name = $idOrRow->name;

       // etc.  

    }

}


查看完整回答
反对 回复 2019-10-23
  • 3 回答
  • 0 关注
  • 772 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信