简体   繁体   中英

PDO Statement does not work anymore in PHP 7

When I switch from PHP 5.6 to 7.0 or 7.2., this statement does not work anymore:

$translator = new stdClass();

$sql = "SELECT name, value FROM ".$tab_translator." WHERE lang_id=:lang_id";
try {
    $fetchTextTranslated = $conn->prepare($sql);
    $fetchTextTranslated->bindValue(':lang_id', (int) trim($translator_lang_id), PDO::PARAM_INT);
    $fetchTextTranslated->execute();
    }
catch(PDOException $e) {
if ($config->debug==1) { echo 'Error: ' . $e->getMessage(); }}

while ($textTranslated = $fetchTextTranslated->fetch(PDO::FETCH_ASSOC)) {
   $translator->$textTranslated['name']=$textTranslated['value'];
}

When I echo $textTranslated['name'] or $textTranslated['value'] I do get data from the table. But I want fetched-data to be in the form of stdClass object $translator and this does not work anymore in PHP 7 and higher.

I would appreciate your help.

I'd just like to mention that the use of variable variables is generally a symptom of suboptimal data storage architecture, but there may also be some fringe cases where an advantage may be gained. Generally though, try to avoid variable variables whenever possible.

Please read about Uniform Variable Syntax .

https://www.oreilly.com/ideas/upgrading-to-php7#uniform_variable_syntax

You must wrap your dynamic property in curly braces.

$translator->{$textTranslated['name']} = $textTranslated['value'];
//           ^-----------------------^

This clears up potential confusion/inconsistency when trying to evaluate the line. Again, see my linked document.


I mean, your code could intend to do something entirely different like:

You want to store data as the element with the key name in the $translator->$textTranslated property (a variable property). ...you don't, but I'm just saying, this php7 improvement removes ambiguity while reading left-to-right.

For the record, here is the syntax for the alternative (which you shouldn't use for your task):

 ($translator->$textTranslated)['name'] = $textTranslated['value'];

See the difference?


Additional references:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM