2017-06-11 43 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

相關問題