Read stdClass property dynamic defined by string

Costas

Administrator
Staff member
stdClass with reflection not working
JavaScript:
$stmt->bindValue(':id', $row->getProperty('player'));

using notation is working
JavaScript:
//src - https://drupalize.me/blog/201508/dynamically-access-php-object-properties
foreach($entity->response as $row)
{
	//before
		$stmt->bindValue(':id', $row->player->id);
	//after
		$stmt->bindValue(':id', $row->{'player'}->{'id'});
}

notation rev2 - extend it
JavaScript:
//keys are the DB Fields
//the sub arrays are the stdClass properties

    $fields = array(
        'id' => array('player','id'),
        'firstname' => array('player', 'firstname'),
        'lastname' => array('player', 'lastname'),
        'address' => array('player', 'address', 'name')
    );
    
        if ($stmt = $db->getConnection()->prepare($insert_sql)){

            foreach($entity->response as $row)
            {
                foreach($fields as $key => $value) 
                {
                    $stmt->bindValue(":$key" , BindBlind($row, $value));
                }
                
                $stmt->execute();
            }
            
        }
        
        
function BindBlind($r, $arr)
{
    $rowVal = null;

    foreach($arr as $f) {
        if (!$rowVal)
            $rowVal = $r->{$f};
        else 
            $rowVal = $rowVal->{$f};
    }

    return  $rowVal;
}

#stdClass #getproperty #reflection
 
Top