首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >类实例化中的空参数

类实例化中的空参数
EN

Stack Overflow用户
提问于 2014-02-21 16:53:46
回答 3查看 74关注 0票数 1

我很少在PHP中使用类,所以请原谅我的无知。

我有一个包含各种函数的类,其中包含返回值。在类的开头,我有一个用于创建类函数中使用的变量的构造器。就像这样:

代码语言:javascript
运行
复制
function __construct($firstVariable,$secondVariable,$thirdVariable)  {

     if(isset($firstVariable)) { $this->firstname = $first; };
     if(isset($secondVariable)) { $this->secondname = $second; };
     if(isset($thirdVariable)) { $this->thirdname = $third; };
}

因此,我的问题是:如果我只打算使用$secondVariable怎么办?我理解在类实例化时可以执行以下操作:

代码语言:javascript
运行
复制
$Class = new classname(NULL,$secondVariable,NULL);

但我觉得这是不恰当的或低效的。使用此方法,每次不想使用变量时,我都需要传递NULL .当我在不同的页面上使用类的变体时,这种情况会发生很多。例如,第1页使用第二个参数,而第2页使用第三个参数。#3使用这三种方法。

所以..。

代码语言:javascript
运行
复制
#1: $Class = new classname(NULL,$secondVariable,NULL);
#2: $Class = new classname(NULL,NULL,$thirdVariable);
#3: $Class = new classname(#firstVariable,$secondVariable,$thirdVariable);

好吧,这很好,但是如果我在类中添加一个新函数,它需要它自己的变量,因此需要第四个参数,那会怎么样呢?我需要返回并在未使用这个新函数的所有类实例化中添加'NULL‘作为第四个参数(并防止php抛出错误,因为该类需要第四个参数)。当然,这不可能是PHP最佳实践!

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2014-02-21 16:56:05

我觉得这个应该能行吧?

代码语言:javascript
运行
复制
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);。其余的将自动默认为空。

如果然后将函数更改为包含更多变量:

代码语言:javascript
运行
复制
function _construct($firstVariable=NULL,$secondVariable=NULL,$thirdVariable=NULL,$fourthVariable=NULL) {

不会引起任何问题。

票数 3
EN

Stack Overflow用户

发布于 2014-02-21 17:02:14

您可以使用默认参数来满足您的需要。

请参阅现场演示

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

Stack Overflow用户

发布于 2014-02-21 17:08:44

如果您想跳过最后一个参数到第一个参数,请使用BT643答案。但是,如果您只想使用第二个,并跳过前面的,您应该使用工厂方法模式

代码语言:javascript
运行
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21940384

复制
相关文章

相似问题

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