我想使用对象的构造函数将数据加载到对象的实例中,我写
$this->property=$row["colname"]
为每个属性指定时间
mysql_fetch_object函数作为对象获取数据,但我不确定对象的实例是否可以从内部分配给某些对象。否则我会使用
__construct($object) { $this=$object; } //doesn't give any syntax error
也许我应该研究一下属性的迭代并使用
foreach($object as $key => $value) $value=$object[$key];
或者我可以赋值为
$this=$object;
构造函数中的?
你不能给$this
赋值,否则你会得到一个错误。
我会这样做:
class SomeObject
{
function __construct($base = null)
{
if ($base != null)
{
$this->load($base);
}
// continue construction as you normally would
}
function load($object)
{
foreach ($object as $key => $value)
{
$this->$key = $value;
}
}
}
然后您可以选择在构造时将数组加载到对象中,或者在构造之后通过load()
加载数组。
使用例子:
$rows = array('id' => 1, 'name' => 'Foo');
// create an empty SomeObject instance
$obj = new SomeObject();
var_dump($obj);
// load $rows into the object
$obj->load($rows);
var_dump($obj);
// create an instance of SomeObject based on $rows
$rows2 = array('id' => 2, 'name' => 'Bar');
$obj2 = new SomeObject($rows2);
var_dump($obj2);