I am not even sure how to ask. I do this all the time in C# but for the life of me I cannot find any decent examples in PHP. Can you help?
What I am trying to do is for example. Say I have a class called Company who has many Employees.
I want to be able to store all the employees in the company class then later when I iterate through the Company object I need to be able to iterate through all the employees that are assigned to that company and I am having a heck of a time trying to find a straight forward example.
I can populate it, but fro the life of me I cant loop through the Employees. I know I am doing something wrong but cannot figure it out. Here is what I have for example.
Employee
This could be completely wrong for all I know as getting the data back out.
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;
}
}
Company has an array of employees.
In c# I would use something like a generic
public List<Employee> Employees {get;set;}
Then in the constructor I would do something like
Employees = new List<Employee>();
Then I could do something like
foreach(var x in Customer.Employees)
x.first;
That is what I am kind of trying to do.
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;
}
}
Create and populate
$c = new Company("Test");
$c->setEmployee(new Employee('A','B'));
$c->setEmployee(new Employee('C','D'));
$c->setEmployee(new Employee('E','F'));
Up until this point all is well.
To get the name of the company no problem.
echo $c->getCompanyName();
echo "<PRE>";
print_r($c);
echo "</PRE>";
But how do I loop through the employees?
I want to be able to do something like cast Companies employees in a loop to a single Employee then do something like
foreach(customers employees)
echo Employee->getFirst, etc...
Can someone please provide some guidance?
Thanks