Converting a PHP array to class variables

后端 未结 6 1573
说谎
说谎 2020-12-07 10:01

Simple question, how do I convert an associative array to variables in a class? I know there is casting to do an (object) $myarray or whatever it is, but that w

6条回答
  •  借酒劲吻你
    2020-12-07 10:38

    Here's another solution using PDOStatement::fetchObject, though it is a bit of a hack.

    $array = array('property1' => 'value1', 'property2' => 'value2');
    $className = 'MyClass';
    
    $pdo = new PDO('sqlite::memory:'); // we don't actually need sqlite; any PDO connection will do
    $select = 'SELECT ? AS property1, ? AS property2'; // this could also be built from the array keys
    $statement = $pdo->prepare($select);
    
    // this last part can also be re-used in a loop
    $statement->execute(array_values($array));
    $myObject = $statement->fetchObject($className);
    

提交回复
热议问题