Page 1 of 1

php 5 oop tech help needed!

Posted: Mon Jun 26, 2006 8:45 am
by sti
Pimptastic | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


Hi guys newbie here  

 How can i create a class with more than one constructor or at least constructors with different param

Code: Select all

class foo {
    
    public $var;

    // default constructot sets $var to 0
    public function __construct() {
      $this->var = 0;
    }

    //second constr. sets $var to $bar
    public function __construct($bar){
      $this->var = val;
    } 

....

}
Thanks,


Pimptastic | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]

Posted: Mon Jun 26, 2006 9:06 am
by xpgeek
In is inpossible on php.

Just create init function what init you object with different parameters.

Posted: Mon Jun 26, 2006 9:12 am
by Gambler
Either use factory pattern with external initialization, or make use of funtion-handling functions (function_get_args(), etc.).

Posted: Mon Jun 26, 2006 9:20 am
by xpgeek
Gambler wrote:Either use factory pattern with external initialization, or make use of funtion-handling functions (function_get_args(), etc.).
+1
I am forget about factory pattern.
Use them!

Posted: Mon Jun 26, 2006 10:32 am
by Jenk
For your example above, where you have a default value for $bar if no argument is presented upon object instantiation, you can do the following:

Code: Select all

<?php

class Foo
{
    public $bar;

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

$objA = new Foo;
$objB = new Foo('Hello World!');

print($objA->bar); // 0
print($objB->bar); // Hello World!

?>