我可以制作一个PHP函数来创建文本输入字段吗


Can I make a PHP function to create text input fields?

所以我将制作两个带有多个文本输入框的表单,所以我认为制作一个函数来帮助实现自动化是个好主意。

下面是我想出的函数:然而,我得到的结果似乎真的很奇怪,是"回声"和一堆单引号的组合。里面一切看起来都对吗?我是PHP的新手,所以如果我错过了一个明显的错误,我真的很抱歉。

    function makeTextInputField($name)
    {
echo '<label for = "<?php $name ?>"> <?php ucfirst($name) ?> </label><input type = "text" name = "<?php $name?>"></input>';
    }

您不应该在php 中再使用任何标记

function makeTextInputField($name)
        {
    echo '<label for = "'.$name.'">'.ucfirst($name).'</label><input type = "text" name = "'.$name.'" />';
        }

工作演示

因为您可以在PHP中的strings中插入换行符,所以您可以通过使用函数中的变量来提高函数的可读性:

<?php
    function makeTextInputField($name) {
        $text = ucfirst($name);
        echo "
            <label for='{$name}'>{$text}</label>
            <input type='text' name='{$name}' />
        ";
    }
?>

当你想使用它时:

<h1>Welcome</h1>
<?php makeTextInputField('email'); ?>

输出

<h1>Welcome</h1>
<label for='email'>Email</label>
<input type='text' name='email' />

您的问题是在PHP代码中打开了新的PHP标记,而这些标记实际上是不需要的。试试这个功能,看看它是否适合你:

function makeTextInputField($name)
{
    echo sprintf('<label for="%s">%s</label> <input type="text" name="%s"></input>', $name, ucfirst($name), $name);
}

尝试使用sprintf

function textInput($name)
{
  $html = '<label for="%1$s">%2$s</label><input type="text" name="%1$s"/>';
  echo sprintf($html, $name, ucfirst($name));
}
<?php
class DeInput
{
    protected $_format = '<div>
                 <label for="%s">%s</label>
                 <input  class="formfield" type="text"   name="%s"  value="%s">
                 </div>';
        public function render($content,$getFullyQualifiedName,$getValue,$getLabel)
    {
        $name = htmlentities($getFullyQualifiedName);
        $label = htmlentities($getLabel); 
        $value = htmlentities($getValue);
        $markup = sprintf($this->_format, $name, $label,  $name, $value);
        return $markup;
    }

}

将PHP代码放在引号内是一种不好的做法,所以我可以使用(.(点来组合字符串。

这是我的例子:

function makeTextInputField($name) {
    echo '<label for="'. $name .'">'.ucfirst($name).'</label>';
    echo '<input type="text" name="'.$name .' />';
}

使用echo的return整数,它将更容易处理结果。您还可以将元素生成拆分为不同的功能,以获得更大的灵活性:

function createLabel($for,$labelText){
    return '<label for = "'.$for.'"> '.ucfirst($labelText).'</label>';
}
function createTextInput($name,$value,$id){
    return '<input type = "text" name = "'.$name.'" id="'.$id.'">'.$value.'</input>';
}
function myTextInput($name,$value,$labelText){
    $id = 'my_input_'.$name;
    return createLabel($id,$labelText).createTextInput($name,$value,$id);
}
echo myTextInput('email','','Type you email');
function makeTextInputField($name)
{
echo '<label for = "'.$name.'"> '.ucfirst($name).'</label><input type = "text" name = "'.$name.'"></input>';
 }

这应该行得通。

您已经在php中了。因此不需要<?php标签。将字符串与连接在一起。