Page 1 of 1

PHP Associative arrays with objects as values?

Posted: Thu Nov 13, 2008 9:48 am
by devarien
I'm having some trouble with a function in one of my frameworks. I changed the backend to use a properties-based approach with registerable fields instead of extending the class and adding the fields there. However, the function to actually register the field is causing a problem...

Code: Select all

 
class Course {
// snip...
public function RegisterField($fieldName, $fieldDesc){
        echo "Registering field '$fieldName' as '$fieldDesc'...  ";
        $this->$fields[$fieldName] = new DataField($fieldDesc);
        echo "Registered.\n";
}
// snip...
 
When I pull up the page, I see the following:
Registering field 'autoindex' as 'int( 11 ) NOT NULL AUTO_INCREMENT'...
but it never gets to "Registered", and doesn't register any of the fields after that one. I'm not sure why this doesn't work, and from what I've read I can use objects as values in an associative array. Can someone explain what's wrong and/or how to fix it (if it's easily reconciled)?

Other code that might be pertinent:

Code: Select all

 
class DataField {
// snip...
function DataField($field){
        $this->fieldDesc = $field;
        $this->fieldValue = "";
}
// snip...
}
 
(Also, the Course constructor calls $this->RegisterField() on the autoindex; it is not explicitly called after construction. $fields is defined earlier as "$fields = new array();")

Thanks!

Re: PHP Associative arrays with objects as values?

Posted: Thu Nov 13, 2008 10:59 am
by devarien
Whoops. Sorry about that - I was looking over it one last time and noticed $this->$fields instead of $this->fields... That probably has something to do with it.