在PHP中做多个构造函数的最佳方式 [英] Best way to do multiple constructors in PHP

查看:139
本文介绍了在PHP中做多个构造函数的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您不能在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

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

或者如果我有一个数据库数组:

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.

这篇关于在PHP中做多个构造函数的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆