【问题标题】:Constructor Overloading in PHPPHP中的构造函数重载
【发布时间】:2011-12-05 11:51:18
【问题描述】:

问题处理

我有一个这样的类,带有重载的构造函数

代码

<?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);
    }

}


?>

问题详情

上面的代码提供了一个错误:error:Fatal error: Cannot redeclare User::User()

由于其他语言如 C++ 和 Java 使用上述方法来重载构造函数,如何在 PHP OOP 中做到这一点?

其他信息

我在 LAMP 中使用 *PHP 5.3.2 * 此版本应完全支持 OOP 概念

【问题讨论】:

标签: php oop overloading


【解决方案1】:

PHP 没有重载。它有一系列神奇的方法,手册中描述为重载(参见:http://php.net/manual/en/language.oop5.overloading.php),但这不是你想的。

另外,顺便说一句,在 PHP 5+ 中编写构造函数的正确方法是使用 __construct 方法:

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

【讨论】:

    【解决方案2】:

    您根本不能根据参数重载方法。在您的情况下,答案可能就像my answer to a similar question here

    【讨论】:

      【解决方案3】:

      PHP 不支持您从其他语言中知道的重载。相反,您可以使用 func_get_args(); 并进行处理。

      http://www.php.net/func_get_args

      更多关于 PHP 中重载可能性的信息: http://php.net/manual/en/language.oop5.overloading.php

      【讨论】:

        【解决方案4】:

        你可以尝试这样的事情......用例在GitHub gist

        <?php
        use \InvalidArgumentException;
        class MyClass{
            protected $myVar1;
            protected $myVar2;
            public function __construct($obj = null, $ignoreExtraValues = false){
                if($obj){
                    foreach (((object)$obj) as $key => $value) {
                        if(isset($value) && in_array($key, array_keys(get_object_vars($this)))){
                            $this->$key = $value;
                        }else if (!$ignoreExtraValues){
                            throw new InvalidArgumentException(get_class($this).' does not have property '.$key);
                        }
                    }
                }
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-03-30
          • 2012-09-24
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多