Update:
Thanks to an anonymous commenter for letting me know that this is an issue of operator precedence.
This is more a personal note than anything, but I've been banging my head against a wall trying to figure out how to reference an array within a variably-named object property in PHP. Having not found anything very useful when search Google, I figure my post may end up being someone's helpful search result. Maybe I just don't know the right terminology for what I'm trying to do...?
Anyways, I've got a module that needs to modify the string in a CCK text field before it's shown to users on the node edit form. It's a "glue" module that helps us handle course enrollment, and the field in question handles course instructor(s) via a comma-delimited list of usernames. The module takes the user's submitted data, parses it into an array and stores each username in a table joined with course ID for other uses (such as passing to our Sakai installation). The CCK field is referenced in several places, so I use an admin settings form to allow us to say, "This CCK field is the field that users fill out to define instructors." This allows us to avoid hard-coding the CCK field name all over our glue module, but it also led to the headache I encountered today.
When a user goes back to the form to edit the course, I want to present the username list cleanly (alphabetical, no accidental whitespace, etc). Here's the code I tried to use:
function ideal_courses_nodeapi(&$node,$op,$a3=NULL,$a4=NULL){// ... (irrelevant stuff here) case'prepare':$field_instructors= variable_get('ideal_courses_field_instructors',NULL);// The line that fails is below:$node->$field_instructors[0]['value']= ideal_courses_instructors_as_string($node);break; // ... (more irrelevant stuff here)}
The error I kept getting was, "PHP Fatal error: Cannot use string offset as an array." The strange thing is that doing a print_r($node->$field_instructors);
works fine. The fix was simple, but difficult to find: wrap the variable property name in curly braces: $node->{$field_instructors}[0]['value']
. The full result is below:
function ideal_courses_nodeapi(&$node,$op,$a3=NULL,$a4=NULL){// ... (irrelevant stuff here) case'prepare':$field_instructors= variable_get('ideal_courses_field_instructors',NULL);// Fixed line is below:$node->{$field_instructors}[0]['value']= ideal_courses_instructors_as_string($node);break; // ... (more irrelevant stuff here)}