PHP if语句在字符串值内

时间:2018-02-13 00:20:13

标签: php

我不确定这是否可行。如果是的话,我不知道该怎么做。

$input = '<input type="text" name="'.$name.'" value="'.$value.'" '. if($edit == "no"){ echo "readonly"; } .'>';

3 个答案:

答案 0 :(得分:2)

您无法使用if,但您可以使用三元运算符,如下所示:

$input = '<input type="text" name="'.$name.'" value="'.$value.'" '. (($edit == "no") ? "readonly" : "") .'>';

答案 1 :(得分:0)

你这样做的方式,没有。

if($edit == "no"){ $inputAppend = "readonly"; }
else { $inputAppend = ""; }

$input = '<input type="text" name="'.$name.'" value="'.$value.'" '.$inputAppend.'>';

或者,如果你想把它保持在一条线上,Ilya Bursov建议的三元算子就是你要走的路。

答案 2 :(得分:0)

为了摆脱“'。$ var。'”混淆,您可能更喜欢以下其中一种选择:

的sprintf

$input = sprintf("<input type='text' name='%s' value='%s'%s />",
                 $name,
                 $value,
                 $edit=='no' ? 'readonly' : ''
                );

定界符

$readonly = $edit=='no' ? 'readonly' : '';

$input = <<<INPUT
<input type="text" name="$name" value="$value"$readonly />
INPUT;

但我首选的方法是确保你先做你的php计算,然后当这一切都完成后,切换出php并写出html:

php as template

<?php
// do stuff
// assign $name, $value, and $readonly
?>
<html>
<!-- html stuff -->
<input type="text" name="<?= $name ?>" value="<?= $value ?>" <?= $readonly ?> />