PHP constructors

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • nitinpatel1117
    New Member
    • Jun 2007
    • 111

    PHP constructors

    Hi

    i'm new to Object Oriented Programming in PHP5, but have done this before in Java and C++.

    I not sure if this is possible in PHP5 but what i'm trying to do is create two constructors in my class. One a default constructor and another a parameterised constuctor. (Firstly, is it possible to have 2 constructors in a class)

    I want the parameterised constructor to call the default constructor, but i can't find any syntax that allows this to be done.

    In the parameterised constructor, I am trying to call the default constructor by using:

    [PHP]$this->__construct( );[/PHP]

    But that does not seem to work;


    Also, at the point that I have declared the second constructor I get the error:

    Fatal error: Cannot redeclare class_name::__c onstruct()
    which suggest that i cannot create another constructor.

    But, if two constructors can't be created in a class, how does one go about implementing a default and parameterised constructor for a class.
  • pbmods
    Recognized Expert Expert
    • Apr 2007
    • 5821

    #2
    Heya, Nitin.

    You can use default values for your parameters:
    [code=php]
    public function __construct( $name = null, $grade = null )
    {
    if( $name ) $this->name = $name;
    if( $grade ) $this->grade = $grade;
    }
    [/code]

    Calling the constructor without specifying any parameters will cause PHP to use the default values (in this case, null). Have your constructor check for nulls to decide whether to use the parameters.

    Or you can simply set the default values as you need; they don't have to be null.

    Comment

    Working...