【发布时间】:2014-10-22 09:37:57
【问题描述】:
我有以下类,它有几个属性和一个 PHP 方法(这是简化的代码)。
class Member{
public $Name;
public $Family;
public function Fetch_Name(){
for($i=0;$i<10;$i++){
$this[$i]->$Name = I find the name using RegExp and return the value to be stored here;
$this[$i]->Family = I find the family using RegExp and return the value to be stored here;
}
}//function
}//class
在函数 Fetch_Name() 中,我想使用 RegExp 查找文本文件中的所有名称和族,并将它们以数组的形式存储为对象的属性。但我不知道我应该如何定义成员的数组。这是合乎逻辑的还是我应该定义 StdClass 或二维数组而不是类?
我发现here 的讨论略有相似,但使用二维数组而不是使用类属性将数据存储在对象中。
我认为我的问题在于定义以下代码行。
$Member = new Member();
$Member->Fetch_name();
我定义的成员不是数组。如果我确实定义了它数组,它仍然不起作用。我这样做了
$Member[]= new Member();
但它给出了错误
致命错误:在非对象中调用成员函数 Fetch_name()
如果我给 $Member[0]= new Member() 那么我不知道如何在 Fetch_Name 函数中创建 $Member1 或 Member[2] 等等。我希望我的问题不是复杂和不合逻辑的。
在此先感谢
【问题讨论】:
-
您可以用来自特定类的对象填充数组,但 PHP 中没有类型数组这样的东西。
-
我需要你解释的。一个可以由类中的对象填充的数组。但我是股票。
-
提供的答案非常好。我只是说你不能真正将数组锁定为只接受一种特定类型的对象。