PHP Associative arrays with objects as values?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
devarien
Forum Newbie
Posts: 2
Joined: Thu Nov 13, 2008 9:02 am

PHP Associative arrays with objects as values?

Post 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!
devarien
Forum Newbie
Posts: 2
Joined: Thu Nov 13, 2008 9:02 am

Re: PHP Associative arrays with objects as values?

Post 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.
Post Reply