我很少在PHP中使用类,所以请原谅我的无知。
我有一个包含各种函数的类,其中包含返回值。在类的开头,我有一个用于创建类函数中使用的变量的构造器。就像这样:
function __construct($firstVariable,$secondVariable,$thirdVariable) {
if(isset($firstVariable)) { $this->firstname = $first; };
if(isset($secondVariable)) { $this->secondname = $second; };
if(isset($thirdVariable)) { $this->thirdname = $third; };
}
因此,我的问题是:如果我只打算使用$secondVariable
怎么办?我理解在类实例化时可以执行以下操作:
$Class = new classname(NULL,$secondVariable,NULL);
但我觉得这是不恰当的或低效的。使用此方法,每次不想使用变量时,我都需要传递NULL
.当我在不同的页面上使用类的变体时,这种情况会发生很多。例如,第1页使用第二个参数,而第2页使用第三个参数。#3使用这三种方法。
所以..。
#1: $Class = new classname(NULL,$secondVariable,NULL);
#2: $Class = new classname(NULL,NULL,$thirdVariable);
#3: $Class = new classname(#firstVariable,$secondVariable,$thirdVariable);
好吧,这很好,但是如果我在类中添加一个新函数,它需要它自己的变量,因此需要第四个参数,那会怎么样呢?我需要返回并在未使用这个新函数的所有类实例化中添加'NULL‘作为第四个参数(并防止php抛出错误,因为该类需要第四个参数)。当然,这不可能是PHP最佳实践!
发布于 2014-02-21 16:56:05
我觉得这个应该能行吧?
function __construct($firstVariable=NULL,$secondVariable=NULL,$thirdVariable=NULL) {
if(isset($firstVariable)) { $this->firstname = $first; };
if(isset($secondVariable)) { $this->secondname = $second; };
if(isset($thirdVariable)) { $this->thirdname = $third; };
}
然后,如果添加更多的参数,它们将默认为NULL,除非另有指定。请注意,即使是空字符串也会覆盖默认的NULL。
因此,对于只使用$secondVariable
的示例,只需执行:$Class = new classname(NULL,$secondVariable);
。其余的将自动默认为空。
如果然后将函数更改为包含更多变量:
function _construct($firstVariable=NULL,$secondVariable=NULL,$thirdVariable=NULL,$fourthVariable=NULL) {
不会引起任何问题。
发布于 2014-02-21 17:02:14
您可以使用默认参数来满足您的需要。
请参阅现场演示
function __construct($firstVariable=NULL,$secondVariable=NULL,$thirdVariable=NULL) {
if(isset($firstVariable)) { $this->firstname = $first; };
if(isset($secondVariable)) { $this->secondname = $second; };
if(isset($thirdVariable)) { $this->thirdname = $third; };
}
发布于 2014-02-21 17:08:44
如果您想跳过最后一个参数到第一个参数,请使用BT643答案。但是,如果您只想使用第二个,并跳过前面的,您应该使用工厂方法模式
class YourClass {
function __construct($firstVariable,$secondVariable,$thirdVariable) {
// define the object here
}
static function createWithSecond($secondVariable) {
return new YourClass(NULL,$secondVariable,NULL);
}
}
// the client code
$obj1 = new YourClass(1,2,3); // use constructor
$obj2 = YourClass::createWithSecond(2); // use factory method
https://stackoverflow.com/questions/21940384
复制相似问题