有没有办法在PHP中使用__construct函数在分层模式中创建多个构造函数。
例如,我想使用构造函数创建请求类的一个新实例
__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的初学者,所以我想得到您对这个主题的建议,看看它是否有效,或者是否有更好的方法来实现它。
我的猜测是,如果需要的话,为了方便起见,我总是可以使用静态函数。
发布于 2015-10-22 07:33:03
只是扩展了你的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 );
}
}发布于 2015-10-22 07:31:14
您可以使用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
}
}发布于 2015-10-22 07:27:09
为什么不从构造函数中调用函数呢?
function __construct( $url ){
//stuff you need
$this->do_first($stuff)
}
function do_first($stuff){
//stuff is done
}https://stackoverflow.com/questions/33270872
复制相似问题