tags:

views:

44

answers:

2

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  A: 

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'];
Emil Vikström
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?
martin
+1  A: 

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
rikh
That confused me as well.. he basically has a class member named "5". :P
Ian
I thought that was on purpose? But maybe I'm wrong?
Emil Vikström
It apparently is since he did it twice, but I'm pretty sure he doesn't realize what the extra dollar sign does..
Ian
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.
martin