2010-12-22 99 views
-1

我想再次調用__construct函數在我班上通過PHP中的類的另一個函數再次調用構造類?

是這樣的:

class user{ 
    function __construct($ID = null) 
    { 
     if($ID){ 
      //code 
     } 

    function findUser() 
    { 
     //code 
     $this->__construct($ID); 
    } 
} 
當然

,這並不工作,但什麼是做這種正確的方法是什麼?

+1

`$ this - > __ construct($ ID)`will be working,you need按名稱調用函數。當然,構造函數只能被調用一次。 [@zerkms](http://stackoverflow.com/questions/4505542/call-the-construct-class-again-trough-another-function-of-the-class-in-php/4505560#4505560)有權利回答。 – deceze 2010-12-22 01:55:38

+0

這是行不通的,因爲你錯過了兩個下劃線。 – BoltClock 2010-12-22 01:59:37

+0

這是一個錯字:)我只是修復它 – Mars 2010-12-22 02:29:28

回答

4

如果你想覆蓋當前情況下的電流值,我會做:

class user{ 
    function __construct($ID = null) 
    { 
     $this->reinit($ID); 
    } 

    function reinit($id) 
    { 
     if($id) { 
      //code 
     } 
    } 
} 
5
class user{ 
    function __construct($ID = null) 
    { 
     if($ID){ 
      //code 
     } 

    static function find($id) 
    { 
     return new user($id); 
    } 
} 

$user = user::find(42); 
+0

+1這是要走的路,如果你打算應用像工廠模式的東西。 – BoltClock 2010-12-22 01:59:11

0

嘗試:

function findUser(){ 

    self::__construct($ID); 
} 
2

重命名功能,這樣就可以把它叫做:

class user { 
    function __construct($ID = null) 
    { 
     $this->initialize($ID); 
    } 

    private function initialize($ID = null) 
    { 
     if($ID){ 
      //code 
    } 

    function findUser() 
    { 
     //code 
     $this->initialize($ID); 
    } 
} 
相關問題