简体   繁体   English

快速PHP问题

[英]Quick PHP question

I have the following excerpt: 我摘录如下:

if (empty($last_db_error)) {
    echo "OK";
} else {
    echo "Error activating subscription.";
    echo "{$last_db_error}";
}

The problem is that "{$last_db_error}" is not shown, unless I use just $last_db_error , without the quotes and brackets. 问题是除非我仅使用$last_db_error而不使用引号和括号,否则不会显示"{$last_db_error}" Am I missing something here? 我在这里想念什么吗? Isn't the above syntax correct? 上面的语法不正确吗?

The brackets and the quotes are useless in this case. 在这种情况下,括号和引号没有用。

if (empty($last_db_error)) {
    echo "OK";
} else {
    echo "Error activating subscription.";
    echo $last_db_error;
}

Will do the job perfectly. 会做得完美。

BTW, even if you do can put $vars insides quotes in PHP, this is not recommended because : 顺便说一句,即使您可以在PHP中将$vars放在引号内,也不建议这样做,因为:

  • It works for double quotes only, single quotes will display the var name, which leads to error. 它仅适用于双引号,单引号将显示var名称,这会导致错误。
  • It slows down the string parsing. 它减慢了字符串解析的速度。

It's much more appropriate to concatenate variables using the dot operator : 使用点运算符连接变量更为合适:

if (empty($last_db_error)) {
    echo "OK";
} else {
    echo "Error activating subscription.\n".
          $last_db_error;
}

And as soon as you have a lot of text to deal with, I urge you to use the PHP alternative syntax . 并且,一旦您要处理大量文本,我敦促您使用PHP替代语法 EG : EG:

<?php if (empty($last_db_error)): ?>
        OK
<?php else : ?>
        Error activating subscription.
        <?php echo $last_db_error; ?>
<?php endif; ?>

Is $last_db_error a string or object? $ last_db_error是字符串还是对象? If it is a string it should display properly between double quotes using curly braces (like you posted above) so the code seems correct. 如果是字符串,则应该使用花括号将双引号正确显示(如您在上面发布的内容),因此代码似乎正确。

Place a var_dump($last_db_error) in the else statement and see what it outputs. 将一个var_dump($last_db_error)放在else语句中,然后查看其输出。

Just use 只需使用

echo $last_db_error; 

the rest is not needed here. 剩下的就不需要了。

The curly brackets are used to evaluate more complex variable names. 大括号用于评估更复杂的变量名称。 If you want the curly brackets in the output, then try escaping the them, like so: 如果要在输出中使用大括号,请尝试转义大括号,如下所示:

if (empty($last_db_error)) {
    echo "OK";
} else {
    echo "Error activating subscription.";
    echo "\{$last_db_error\}";
}

For me it works ok: 对我来说,它可以正常工作:

<?php
$last_db_error = "LLLLLLLLLLLL";
echo "{$last_db_error}";

It shows me LLLLLLLLLLLL 它告诉我LLLLLLLLLLLL

也许您正在使用某种模板系统来解析{ .... }内部的所有内容?

The simpliest way is: 最简单的方法是:

echo $last_db_error;

For some situations try these: 在某些情况下,请尝试以下操作:

 echo "${last_db_error}";
 echo ${'last_db_error'};

Here is a good article regarding php variable names: curly braces 这是一篇关于php变量名称的好文章:花括号

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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