Reputation: 23
I have two classes, Emp and Dep. I want to get a result something familiar to this:
$objDep = new Dep();
$objDep->SetName('Sales');
$objEmp = new Emp();
$objEmp->SetDep($objDep);
$objDep->GetEmps()->Add($objEmp);
$objDep->GetEmps(0)->GetDep()->GetName(); //result 'sales'
I have written this in Dep class:
...
public $_emps = array();
...
...
public function GetEmps() {
$params = func_get_args();
$numargs = func_num_args();
if (func_num_args()) {
return $this->_emps[$params[0]];
}
function Add($new_emp)
{
array_push($this->_emps,$new_emp);
}
}
...
and a I'm having an error:
Fatal error: Call to a member function Add() on a non-object.
What is wrong with this code?
Maybe this is simple but I'm new in PHP and I want to complete my exercise for classes.
Upvotes: 0
Views: 201
Reputation: 10975
If you want to chain methods, you will want to return $this
.
Example:
public function GetEmps() {
$params = func_get_args();
$numargs = func_num_args();
if (func_num_args()) {
return $this->_emps[$params[0]];
}
return $this;
}
public function Add($new_emp) {
array_push($this->_emps,$new_emp);
return $this;
}
You may also chain Add, which can result in $obj->Add($emp1)->Add($emp2)->Add($emp3)->getEmps()
.
You will need to make the function Add
a member of the class as well.
Upvotes: 1