带参数的PHP构造函数 [英] PHP constructor with a parameter
问题描述
我需要一个可以执行以下操作的函数:
I need a function that will do something like this:
$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创建参数化的构造函数.
I don’t know how to make a parametrized constructor in PHP.
现在我使用这样的构造函数:
Now I use a constructor like this:
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;
}
}
推荐答案
阅读所有 构造函数和析构函数 .
Read all of Constructors and Destructors.
构造函数可以像使用PHP中的任何其他函数或方法一样采用参数:
Constructors can take parameters like any other function or method in PHP:
class MyClass {
public $param;
public function __construct($param) {
$this->param = $param;
}
}
$myClass = new MyClass('foobar');
echo $myClass->param; // foobar
您的构造函数用法示例现在甚至无法编译,因为您无法重新分配$this
.
Your example of how you use constructors now won't even compile as you can't reassign $this
.
此外,每次访问或设置属性时都不需要大括号. $object->property
正常工作.您只需要在特殊情况下使用花括号,例如,如果您需要评估方法$object->{$foo->bar()} = 'test';
Also, you don't need the curly brackets every time you access or set a property. $object->property
works just fine. You only need to use curly-brackets under special circumstances like if you need to evaluate a method $object->{$foo->bar()} = 'test';
这篇关于带参数的PHP构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!