我需要能做类似这样的事情:
$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;
Run Code Online (Sandbox Code Playgroud)
当我写这样的东西时:
$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
Run Code Online (Sandbox Code Playgroud)
我不知道如何在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;
}
}
Run Code Online (Sandbox Code Playgroud)
Mik*_*e B 125
阅读所有这些http://www.php.net/manual/en/language.oop5.decon.php
构造函数可以像php中的任何其他函数或方法一样获取参数
class MyClass {
public $param;
public function __construct($param) {
$this->param = $param;
}
}
$myClass = new MyClass('foobar');
echo $myClass->param; // foobar
Run Code Online (Sandbox Code Playgroud)
您现在使用构造函数的示例甚至无法编译,因为您无法重新分配$this.
此外,每次访问或设置属性时都不需要花括号.$object->property工作得很好.您只需要在特殊情况下使用花括号,例如需要评估方法$object->{$foo->bar()} = 'test';
Mic*_*son 21
如果要将数组作为参数传递,并且"auto"填充属性:
class MyRecord {
function __construct($parameters = array()) {
foreach($parameters as $key => $value) {
$this->$key = $value;
}
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,构造函数用于创建和初始化对象,因此可以$this使用/修改正在构造的对象.