首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP中的便捷构造函数

PHP中的便捷构造函数
EN

Stack Overflow用户
提问于 2015-10-22 07:19:59
回答 3查看 98关注 0票数 4

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

例如,我想使用构造函数创建请求类的一个新实例

代码语言:javascript
复制
__construct( $rest_noun, $rest_verb, $object_identifier, $additional_arguments );

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

代码语言:javascript
复制
__construct( $url );

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

我猜我的实现应该是这样的:

代码语言:javascript
复制
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的初学者,所以我想得到您对这个主题的建议,看看它是否有效,或者是否有更好的方法来实现它。

我的猜测是,如果需要的话,为了方便起见,我总是可以使用静态函数。

EN

回答 3

Stack Overflow用户

发布于 2015-10-22 07:33:03

只是扩展了你的Request类:

代码语言:javascript
复制
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 );
       }
}
票数 3
EN

Stack Overflow用户

发布于 2015-10-22 07:31:14

您可以使用Best way to do multiple constructors in PHP中提到的func_get_args来做一些事情

代码语言:javascript
复制
function __construct($param) {
    $params = func_get_args();
    if (count($params)==1) {
        // do first constructor
    } else {
        // do second constructor
    }
}
票数 1
EN

Stack Overflow用户

发布于 2015-10-22 07:27:09

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

代码语言:javascript
复制
function __construct( $url ){
   //stuff you need
   $this->do_first($stuff)
}

function do_first($stuff){
   //stuff is done
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33270872

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档