amitmerchant1990 / amitmerchant-dot-com-comments

1 stars 0 forks source link

multiple-constructors-php/ #10

Open utterances-bot opened 3 years ago

utterances-bot commented 3 years ago

Multiple constructors in PHP – Amit Merchant – A blog on PHP, JavaScript and more

Constructors are a really important part of the class-based object oriented programming. Through constuctors, a newly created objects initialize properties automatically before it is usable. In PHP, a constructor is a method named __construct(), which the keyword new automatically calls after creating the object. Constructors can also accept arguments, in which case, when the new statement is written, you also need to send the constructor arguments for the parameters.

https://www.amitmerchant.com/multiple-constructors-php/

yaddly commented 3 years ago

Hi, thank you for your informative and educative site. I'm new to PHP and found this site helpful. I have one question regarding this technique to achieve multiple constructors. How well does this work with inheritance? I'm getting this warning : Parent Constructor is Called

class User { //put your code here

public $name, $password;

function __construct() {
    $arguments = func_get_args(); //Gets an array of the function's argument list.

    $numberOfArguments = func_num_args();//Gets the number of arguments passed to the function.

    if(method_exists($this, $function = '__construct'.$numberOfArguments))
    {
        call_user_func_array(array($this, $function), $arguments);//Calls the callback given by the first parameter with the parameters in args
    }
}

function __construct1($userName) {
    $this->name = $userName;

    $this->password = null;
}

function __construct2($userName, $userPassword) {
    $this->name = $userName;

    $this->password = $userPassword;
}

function save_user()
{
    echo $this->name . " has been saved to the database.";
}

function get_password() {
    return $this->password;
}

function __destruct() {
    $this->name = null;

    $this->password = null;

    //Alternatively
    $this = null;
}

}

class Subscriber extends User {

//put your code here

public $phone, $email;

function __construct($user_name, $user_password, $user_phone, $user_email) {
    parent::__construct($user_name, $user_password);

    $this->phone = $user_phone;

    $this->email = $user_email;
}

function display() {
    echo "Name: " . $this->name . "<br>";
    echo "Pass: " . $this->password . "<br>";
    echo "Phone: " . $this->phone . "<br>";
    echo "Email: " . $this->email;
}

}

HunterShenep commented 2 years ago

This doesn't work for me. PHP version: 7.4.23 Fatal error: Cannot redeclare Admin::__construct() in C:\redacted\includes\AdminDataAccess.inc.php on line 40

takeshiomd commented 2 years ago

You can delete underscore part of function instead of __construct, use public function construct1, construct2 ... and it will work.

takeshiomd commented 2 years ago

This was answer for you @HunterShenep