#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    31
    Rep Power
    3

    Using a variable as a variable name inside class


    Here's what I'm trying to do: convert an object's old property names to new property names based on an associative array.
    Array('ID' => 'guid', 'user_login' => 'username');

    So,
    $row->username= 'michael';

    becomes

    $row->user_login= 'michael';

    (I am actually converting them back)

    To do this, I pass the object, which is created by an SQL query and mysql_fetch_object(), into my custom function convert_results( $obj );

    Here are the relevant sections of the class:
    PHP Code:
    $users_table = Array(
       
    'ID'             =>   'guid',
       
    'user_login'   =>    'username'
       
    'user_pass'   =>    'password' 
    );

    private function 
    query_users($query) {
        
    $this->result = @mysql_query$query$this->dbh );
        
    $num_rows 0;
        while ( 
    $row = @mysql_fetch_object$this->result ) ) {
            
    // Convert the Object to the Wordpress object
            
    $this->last_result[$num_rows] = $this->convert_result$row );
        
    $num_rows++;
        }
    }
    private function 
    convert_result($row) {
        
    $new_row = clone $row;        
        foreach ( 
    $row as $key => $value ) {
            
    // Find the corresponding property name by value in the array.
            
    $var array_search$key$this->users_table );

            
    // Set the new property
            
    $new_row->$var $value;

            
    // Destroy the old property
            
    unset( $new_row->$key );
        }
    return 
    $new_row;

    Everything works until $new_row->$var = $value;
    I don't even get an error, just a 500 Server Error.
    Is there another way to set a property using a variable name?

    Thank you for the help.
  2. #2
  3. Nosey Moderator
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    14,545
    Rep Power
    9415
    You don't handle the case where array_search() cannot find the column name in the array.

    Looping through $users_table would be easier...
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    31
    Rep Power
    3

    Worked perfectly


    Originally Posted by requinix
    You don't handle the case where array_search() cannot find the column name in the array.

    Looping through $users_table would be easier...
    Thank you. That is much more elegant and works great.

IMN logo majestic logo threadwatch logo seochat tools logo