PHP oop构造可选参数语法错误


php oop construct optional parameters syntax error

我正在学习php oop,通过阅读书籍等,并尝试自己的。

在我的__construct中,我有许多具有默认值的参数(实际上它们都具有默认值)。然而,当我试图写代码来创建一个新的对象,我有语法错误的问题。

例如,我的construct语句有6个参数。我将值传递给前三个,想跳过后面两个并为最后一个设置值。我只是把逗号放在它们之间,但它会抛出一个语法错误。

我应该用什么代替什么来接受默认值?

谢谢

传递NULL而不是none

的例子:

$obj = new Whatever($parm1,$parm2,$parm3,NULL,NULL,NULL); 

或在构造函数中设置为null

__construct($parm1 = NULL,$parm2 = NULL,$parm3 = NULL,$parm4 = NULL,$parm5 = NULL,$parm6 = NULL)

然后这样命名

 $obj = new Whatever();   

更新你的评论:

代码:

function __construct(
    $userid, 
    $magicCookie, 
    $accessLvl = 'public', 
    $det       = 'basic', 
    $sortOrder = 'starttime', 
    $recurring = 'true', 
    $d_from    = "01/01/2011", 
    $d_to      = "31/01/2011", 
    $max       = "10") {
    // Code goes here...
} 

所以像这样调用

// After the seconds parameter you have default values
$obj = new Whatever(
    $userid, 
    $magicCookie
    );  

你觉得这个怎么样?

function __construct(
    $userid, 
    $magicCookie, 
    $accessLvl = NULL, 
    $det       = NULL, 
    $sortOrder = NULL, 
    $recurring = FALSE, 
    $d_from    = NULL, 
    $d_to      = NULL, 
    $max       = NULL) {
    // Code goes here... Yes set Defaults if NULL
}

这样写:

$obj = new Whatever(
    $userid, 
    $magicCookie, 
    $accessLvl = 'public', 
    $det       = 'basic', 
    $sortOrder = 'starttime', 
    $recurring = TRUE, 
    $d_from    = "01/01/2011", 
    $d_to      = "31/01/2011", 
    $max       = 10);     

尝试传递空引号。您可能必须在构造函数中使用逻辑来检查空白并设置值。三元运算符()?

Phil发布的解决方案可能是您所追求的,因为您不尊重构造函数的每个参数,即使可能没有值。

既然你正在学习OOP,我想为你提供另一种解决方案。多年来,我发现将参数传递给构造函数最终会导致arg列表变得笨拙。考虑以下示例(仅用于演示目的):

class Car
{
    public function __construct($color = NULL, $transmission = NULL, $bodyStyle = NULL, $interior = NULL, $engineType = NULL, $wheelSize = NULL, $radioType = NULL) {
        // Do stuff
    }
}

对于传递给arg的一长串参数,我实例化的每个对象都必须检查以确保我以正确的顺序传递值,如果我有一段时间没有看到代码,这将变得乏味。

// Example 1
$myCar = new Car('blue', 'automatic', 'sedan', 'leather', 'v6', '18', 'xmBluetooth');
// Example 2
$myCar = new Car('green', 'manual', NULL, NULL, 'v8', NULL);
// Example 3
$myCar = new Car(NULL, NULL, 'sedan', NULL, NULL, NULL, NULL, 'cdPlayer');

我建议使用setter来设置这些值,然后每次实例化对象时,只需要设置必要的值,而不必处理长参数列表中的条目顺序。

class Car {
    protected $color;
    protected $bodyStyle;
    protected $transmission;
    protected $interior;
    protected $engineType;
    protected $wheelSize;
    protected $radioType;
    public function setColor($color) 
    {
        $this->color = $color;
    }
    public function setTransmission($transmission)
    {
        $this->transmission = $transmission;
    }

    // etc.
}
// Calling code
$myCar = new Car();
$myCar->setColor('green');
$myCar->setWheelSize('18');
$myCar->setInterior('leather');
$myCar->setEngineType('v6');
$yourCar = new Car();
$yourCar->setColor('black');

只是考虑一下。