-2

I want to call the __construct function again in my class

something like this:

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

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

of course this does not work, but what is the correct way to do this?

Mars
  • 4,197
  • 11
  • 39
  • 63
  • 1
    `$this->__construct($ID)` will work, you need to call the function by its name. Of course, the constructor should only be called once. [@zerkms](http://stackoverflow.com/questions/4505542/call-the-construct-class-again-trough-another-function-of-the-class-in-php/4505560#4505560) has the right answer. – deceze Dec 22 '10 at 01:55
  • It wouldn't work because you missed out the two underscores. – BoltClock Dec 22 '10 at 01:59
  • that's a typo :) I just fixed it – Mars Dec 22 '10 at 02:29

4 Answers4

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

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

$user = user::find(42);
zerkms
  • 249,484
  • 69
  • 436
  • 539
  • +1 This is the way to go if you intend to apply something like the factory pattern. – BoltClock Dec 22 '10 at 01:59
  • this works but it would be more complecated for me to do it this way, because my function also returns a true or false if the user is found or not. so I used codeThis' method and return true when the user is found and call an init function – Mars Dec 22 '10 at 02:25
  • @mars: if user is not found - return null, otherwise return user instance. After that you can just check `is_null($user)` to see, if it was found or not. – zerkms Dec 22 '10 at 02:35
4

If you want to overwrite the current values in the current instance, I would do this:

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

    function reinit($id)
    {
        if($id) {
            //code
        }
    }
}
zsalzbank
  • 9,685
  • 1
  • 26
  • 39
3

Rename the function so that you can call it:

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

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

    function findUser()
    {
        //code
        $this->initialize($ID);
    }
}
Jon
  • 428,835
  • 81
  • 738
  • 806
0

Try:

function findUser(){

   self::__construct($ID);
}