【发布时间】:2010-08-02 00:06:59
【问题描述】:
我什至不知道该怎么问。我一直在 C# 中这样做,但在我的一生中,我在 PHP 中找不到任何像样的示例。你能帮忙吗?
例如,我正在尝试做的是。假设我有一个名为 Company 的类,它有很多员工。
我希望能够将所有员工存储在 company 类中,然后当我遍历 Company 对象时,我需要能够遍历分配给该公司的所有员工,并且我有很多一段时间试图找到一个直接的例子。
我可以填充它,但从我的生活中我无法遍历员工。我知道我做错了什么,但无法弄清楚。这是我的例子。
员工
据我所知,这可能是完全错误的,因为要恢复数据。
class Employee
{
private $first;
private $last;
public function __construct($first = null, $last = null)
{
if(isset ($first))
$this->first = $first;
if(isset ($last))
$this->last = $last;
}
public function getEmployee()
{
return Employee($this->first, $this->last);
}
public function getFirst()
{
return $this->first;
}
public function getLast()
{
return $this->first;
}
}
公司有很多员工。
在 c# 中我会使用类似泛型的东西
public List<Employee> Employees {get;set;}
然后在构造函数中我会做类似的事情
Employees = new List<Employee>();
然后我可以做类似的事情
foreach(var x in Customer.Employees)
x.first;
这就是我想要做的。
class Company
{
private $companyName;
private $employees;
public function __construct($nameOfCompany)
{
$this->companyName = $nameOfCompany;
}
public function setEmployee(Employee $employee)
{
$this->employees[] = $employee;
}
public function getCompanyName()
{
return $this->companyName;
}
public function setCompanyName($nameOfCompany)
{
$this->companyName = $nameOfCompany;
}
public function getEmployees()
{
return $this->employees;
}
}
创建和填充
$c = new Company("Test");
$c->setEmployee(new Employee('A','B'));
$c->setEmployee(new Employee('C','D'));
$c->setEmployee(new Employee('E','F'));
到目前为止一切都很好。
获取公司名称没问题。
echo $c->getCompanyName();
echo "<PRE>";
print_r($c);
echo "</PRE>";
但我如何循环访问员工?
我希望能够做一些事情,比如将公司员工循环投射到单个员工,然后做类似的事情
foreach(customers employees)
echo Employee->getFirst, etc...
有人可以提供一些指导吗?
谢谢
【问题讨论】:
标签: php oop programming-languages class arraycollection