2017-06-11 44 views
1

即时通讯工作与PHP和MySQL,有时我需要实例化我的PHP类在数据访问层返回对象,加载列表等......但有时我使用类构造函数和其他人不。可以在php类中创建构造函数doble吗?

我可以在类中创建doble构造函数吗?

例如:

class Student { 

private $id; 
private $name; 
private $course; 

function __construct() { 

} 

//get set id and name 

function setCourse($course) { 
    $this->course = $course; 
} 


function getCourse() { 
    $this->course = $course; 
} 

} 

class Course { 

private $id; 
private $description; 

function __construct($id) { 
    this->id = $id; 
} 

//get set, id, description 

} 

在我的接入层有时我使用构造函数以不同的方式 例如:

 $result = $stmt->fetchAll(); 
     $listStudent = new ArrayObject(); 

     if($result != null) { 

      foreach($result as $row) { 

       $student = new Student(); 

       $student->setId($row['id']); 
       $student->setName($row['name']); 
       $student->setCourse(new Course($row['idcourse'])); //this works 

       $listStudent ->append($sol); 
      } 
      } 

但有时我需要使用构造以另一种方式,例如我的英语很差, 我希望你明白我的

+0

你的英语很好,但我不明白你想达到什么目的。你想创建一个具有两个(或更多)构造函数的类吗? – axiac

+0

构造函数的目的是初始化对象的属性,以使其可以使用。在'Student'类中发生的空构造函数(+ setter)是伪装成OOP的程序编程的标志。将'Student'属性的初始化放入其构造函数中,并删除这些setters。 – axiac

+0

嗨,我想要实现的是创建对象与构造函数,并没有构造函数,没有原因的错误...例如: $ course = new Course(); - >作品 和 $ course = new Course($ id); - >也可以工作 但是因为我有ir不工作: $ course = new Course(); - >不工作 和 $ course = new Course($ id); - >作品 感谢您的时间 –

回答

0

使用default arguments

class Course { 

    private $id; 
    private $description; 

    function __construct($id = 0) { 
    this->id = $id; 
    } 

    // getters and setters for id and description 

} 

现在,你可以用它这样的:

$course = new Course(12); // works with argument 

或:

$course = new Course(); // works without argument 
$course->setId(12); 
+0

好的,但我的想法是在一些函数中减少代码,例如: https://paste2.org/kbt56aBW –

+0

因此,在某些情况下,您根本不想调用构造函数? – PeterMader

0
class Course { 

    private $id; 
    private $description; 

    public function __construct() { 
      // allocate your stuff 
     } 

    public static function constructWithID($id) { 
      $instance = new self(); 
      //do your stuffs here 
      return $instance; 
     } 

调用,比如Course :: constructWithID(.. id)whe ñ你必须通过ID,否则使对象(新课程())。

+0

amm我明白...是好的做法? –

+0

静态方法'constructWitID()'也被称为“命名构造函数”。这本身并不坏(或好)*本身*。您使用它(和常规构造函数)创建新对象的方式是可以分类为好或不好练习的部分。 – axiac

相关问题