Constructor overload in PHP

Problem when approaching

I have a class like this with overloaded constructors

the code

<?php /* Users Abstract Class */ abstract class User { protected $user_email; protected $user_username; protected $user_password; protected $registred_date; //Default constructor function User() { } //overloded constructor function User($input_username,$input_email,$input_password) { __set($this->user_username,$input_username); __set($this->user_email,$user_password); __set($this->user_password,$input_password); } } ?> 

Problem Details

The above code contains the error: error:Fatal error: Cannot redeclare User::User()

Like other languages, such as C ++ and Java, use the above approach to overload constructors, how to do it in PHP OOP ?

Additional Information

Im using * PHP 5.3.2 in LAMP * which OOP concepts should be fully supported in this version

+7
source share
3 answers

PHP has no overload. It has a number of magic methods that are described as overloading in the manual (see http://php.net/manual/en/language.oop5.overloading.php ), but that’s not what you think of.

Also, aside, the correct way to write a constructor in PHP 5+ is to use the __construct method:

 public function __construct(/* args */) { // constructor code } 
+10
source

You cannot completely overload methods based on their arguments. in your case the answer may be as simple as my answer to a similar question here

+3
source

Overloading, as you know, from other languages, is not supported in PHP. Instead, you can use func_get_args(); and work with him.

http://www.php.net/func_get_args

Additional information on overload capabilities in PHP: http://php.net/manual/en/language.oop5.overloading.php

+1
source

All Articles