php 5 oop tech help needed!

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
sti
Forum Newbie
Posts: 1
Joined: Mon Jun 26, 2006 8:36 am

php 5 oop tech help needed!

Post 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]
User avatar
xpgeek
Forum Contributor
Posts: 146
Joined: Mon May 22, 2006 1:45 am
Location: Kyiv, Ukraine
Contact:

Post by xpgeek »

In is inpossible on php.

Just create init function what init you object with different parameters.
Gambler
Forum Contributor
Posts: 246
Joined: Thu Dec 08, 2005 7:10 pm

Post by Gambler »

Either use factory pattern with external initialization, or make use of funtion-handling functions (function_get_args(), etc.).
User avatar
xpgeek
Forum Contributor
Posts: 146
Joined: Mon May 22, 2006 1:45 am
Location: Kyiv, Ukraine
Contact:

Post 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!
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post 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!

?>
Post Reply