简体   繁体   中英

Convenience constructor in PHP

Is there a way of using the __construct function in PHP to create more than one constructor in a hierarchical pattern.

For example, I want to create a new instance of my Request class using the constructor

__construct( $rest_noun, $rest_verb, $object_identifier, $additional_arguments );

But I would like a convenience constructor like this:

__construct( $url );

…whereby I can send a URL and the properties are extracted from it. I then call the first constructor sending it the properties I extracted from the URL.

I guess my implementation would look something like this:

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

…but I'm quite a beginner in PHP so wanted to get your advice on the topic to see if it would work or even if there's a better way to do it.

My guess is if it comes down to it I can always just use a static function for my convenience.

Just extends your Request class:

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

why dont you call the function from the constructor?

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

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

You could do something with func_get_args as noted in Best way to do multiple constructors in PHP

function __construct($param) {
    $params = func_get_args();
    if (count($params)==1) {
        // do first constructor
    } else {
        // do second constructor
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM