0

Maybe I am overlooking something, but I stumbled across this:

$employees = new stdClass();

$employee_id = 5;
$employee = array();
$employee["id"] = $employee_id;
$employee["name"] = "John;

$employees->$employee_id = $employee;

Now I want to change the employee Name:

$employee = $employees->$employee_id;
$employee["name"] = "Tom";

Now I have two problems:

  1. The employee object seems not to be passed by reference, because the employee within the employees is still named John.

  2. How would I retrieve the employee name? echo {$employee->$employee_id}["name"]; does not work

Thanks for the help,

Martin

2
  • Why are you using $employees->$employee_id and not $employees->employee_id ? Commented Jan 14, 2010 at 15:42
  • 1.) see comment to answer from Emil. 2.) Why is it stupid code? Of course the employee name will not get changed immediately, but later on in a while loop when mysql data is read out. What would you suggest? Commented Jan 14, 2010 at 16:01

2 Answers 2

2

1) PHP does rarely pass by reference. If you want to force a pass by reference, use the =& operator:

$employees->$employee_id =& $employee;

Read more here: http://php.net/references

2) To use $employees->$employee_id in the first place is rather ugly, but here is a possible solution:

$current_employee =& $employee->$employee_id;
echo $current_employee['name'];
Sign up to request clarification or add additional context in comments.

1 Comment

ad 1) ok. But actually Problem 1) is solved when I solve Problem 2, cause then I can assign it directly. ad 2) Why is this rather ugly? I can not use an associative array, cause when it is send to the Frontend (ZendAMF) the keys do not get maintained, so I need to use an object. Any other ideas?
1

You have an extra $ that should not be there.

//$employees->$employee_id = $employee;     Wrong
$employees->employee_id = $employee;

With the dollar, php uses the value of var. eg...

$name = "car";
$obj->car = 5;
$obj->$name = 10;

echo $obj->car;  // outputs 10

3 Comments

That confused me as well.. he basically has a class member named "5". :P
It apparently is since he did it twice, but I'm pretty sure he doesn't realize what the extra dollar sign does..
thx for the comments. please read the comment I made above. Yes I made it on purpose, for serializing the data properly, as ZendAMF does not treat Associative Arrays with numeric indices. They are not maintained after they are sent over the wire.

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.