带有参数的PHP构造函数

问题描述 投票:48回答:2

我需要一个可以执行以下操作的函数:

$arr = array(); // This is the array where I'm storing data

$f = new MyRecord(); // I have __constructor in class Field() that sets some default values
$f->{'fid'} = 1;
$f->{'fvalue-string'} = $_POST['data'];
$arr[] = $f;

$f = new Field();
$f->{'fid'} = 2;
$f->{'fvalue-int'} = $_POST['data2'];
$arr[] = $f;

当我写这样的东西时:

$f = new Field(1, 'fvalue-string', $_POST['data-string'], $arr);
$f = new Field(2, 'fvalue-int', $_POST['data-integer'], $arr);

// Description of parameters that I want to use:
// 1 - always integer, unique (fid property of MyRecord class)
// 'fvalue-int' - name of field/property in MyRecord class where the next parameter will go
// 3. Data for field specified in the previous parameter
// 4. Array where the class should go

我不知道如何用PHP创建参数化的构造函数。

现在我使用这样的构造函数:

class MyRecord
{
    function __construct() {
        $default = new stdClass();
        $default->{'fvalue-string'} = '';
        $default->{'fvalue-int'} = 0;
        $default->{'fvalue-float'} = 0;
        $default->{'fvalue-image'} = ' ';
        $default->{'fvalue-datetime'} = 0;
        $default->{'fvalue-boolean'} = false;

        $this = $default;
    }
}
php constructor
2个回答
125
投票

读取所有Constructors and Destructors

构造函数可以像PHP中的任何其他函数或方法一样采用参数:

class MyClass {

  public $param;

  public function __construct($param) {
    $this->param = $param;
  }
}

$myClass = new MyClass('foobar');
echo $myClass->param; // foobar

您关于如何使用构造函数的示例现在甚至无法编译,因为您无法重新分配$this

而且,每次访问或设置属性时,都不需要大括号。 $object->property可以正常工作。您仅需要在特殊情况下使用花括号,例如,如果您需要评估方法$object->{$foo->bar()} = 'test';


21
投票

[如果您想将数组作为参数传递,并使用'auto'填充属性:

class MyRecord {
    function __construct($parameters = array()) {
        foreach($parameters as $key => $value) {
            $this->$key = $value;
        }
    }
}

注意,构造函数用于创建和初始化对象,因此可能会使用$this使用/修改要构造的对象。

© www.soinside.com 2019 - 2024. All rights reserved.