带参数的 PHP 构造函数
2022-08-30 09:28:50
我需要一个函数来做这样的事情:
$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;
}
}