PDO Statement does not work anymore in PHP 7

南笙酒味 提交于 2021-01-29 21:51:42

问题


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.


回答1:


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:

  • http://php.net/manual/en/language.variables.variable.php
  • https://www.engineyard.com/blog/what-to-expect-php-7
  • https://wiki.php.net/rfc/uniform_variable_syntax


来源:https://stackoverflow.com/questions/52573821/pdo-statement-does-not-work-anymore-in-php-7

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!