0

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.

3
  • 1
    You might have meant to use $objDep->GetEmps(0)->SetDep()->GetName();? I don't see any other reference to GetDep() Commented Jun 1, 2014 at 0:18
  • Put Add method outside the GetEmps method, so its just another method in the class. Emp's and Dep's makes no sense, a good naming convention and class entity would make it clearer to yourself Commented Jun 1, 2014 at 0:21
  • Plus, there's no other reference to GetName() Commented Jun 1, 2014 at 0:28

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.