PHP中的便捷构造函数

时间:2015-10-21 23:19:59

标签: php constructor

有没有办法在PHP中使用__construct函数以分层模式创建多个构造函数。

例如,我想使用构造函数

创建Request类的新实例
__construct( $rest_noun, $rest_verb, $object_identifier, $additional_arguments );

但我想要一个像这样的便利构造函数:

__construct( $url );

...我可以发送一个URL,并从中提取属性。然后我调用第一个构造函数,向它发送我从URL中提取的属性。

我想我的实现看起来像这样:

function __construct( $rest_noun, $rest_verb, $object_identifier, $additional_arguments )
{
    //
    //  Set all properties
    //

    $this->rest_noun = $rest_noun;
    $this->rest_verb = $rest_verb;
    $this->object_identifier = $object_identifier;
    $this->additional_arguments = $additional_arguments;
}

function __construct( $url )
{
    //
    //  Extract each property from the $url variable.
    //

    $rest_noun = "component from $url";
    $rest_verb = "another component from $url";
    $object_identifier = "diff component from $url";
    $additional_arguments = "remaining components from $url";

    //
    //  Construct a Request based on the extracted components.
    //

    this::__construct( $rest_noun, $rest_verb, $object_identifier, $additional_arguments );
}

...但我是PHP的初学者,所以我希望得到你对这个主题的建议,看看它是否有用,或者即使有更好的方法可以做到这一点。

我的猜测是,如果归结为它,我总是可以使用静态函数来方便我。

3 个答案:

答案 0 :(得分:3)

只需扩展您的Request课程:

class RequestWithAnotherContructor extends Request
{
        function __construct($url) {
            $rest_noun = "component from $url";
            $rest_verb = "another component from $url";
            $object_identifier = "diff component from $url";
            $additional_arguments = "remaining components from $url";

            // call the parent constructors
            parent::__construct( $rest_noun, $rest_verb, $object_identifier, $additional_arguments );
       }
}

答案 1 :(得分:0)

为什么不从构造函数中调用函数?

function __construct( $url ){
   //stuff you need
   $this->do_first($stuff)
}

function do_first($stuff){
   //stuff is done
}

答案 2 :(得分:0)

您可以使用Best way to do multiple constructors in PHP

中提到的func_get_args执行某些操作
function __construct($param) {
    $params = func_get_args();
    if (count($params)==1) {
        // do first constructor
    } else {
        // do second constructor
    }
}