我目前正在为正在编写的脚本编写一些函数。我的问题是,内容的生成方式是由php变量生成的。
因此,要生成页面内容,它必须是这样的:
$contents .="page content inside this";
如果我制作这样的echo
:
echo "page content inside this";
则回显的文本将出现在页面顶部。因此,我必须使用$contents.="";
来生成页面内容。
我目前正在编写一个可以快速生成复选框的函数。我的功能如下:
function checkbox($name, $value, $checked){
if($checked == 1){
$checked = "checked";
}else{
$checked ="";
}
$contents.="<div class='roundedOne'>
<input type='checkbox' value='$value' id='roundedOne' name='$name' $checked />
<label for='roundedOne'></label>
</div>";
}
当我调用页面内的函数时,什么都不会出现:
$contents.="
".checkbox("name","value","1")."
";
我可以想象,当我调用该函数时,没有发生任何事情的原因是我使用了$contents
而不是echo
,但不幸的是,这是我唯一的选择,因为脚本是加密的,所以我无法更改$contents
的行为方式。
我的问题是,如何使用$contents打印函数?
在函数(不推荐)-中使用$contents
之前,需要将其声明为全局
global $contents;
$contents.="<div class='roundedOne'>
<input type='checkbox' value='$value' id='roundedOne'
name='$name' $checked />
<label for='roundedOne'></label>
</div>";
或者,更好的是,你可以从你的功能中生成内容,然后返回它-
function checkbox($name, $value, $checked){
if($checked == 1){
$checked = "checked";
}else{
$checked ="";
}
return "<div class='roundedOne'>
<input type='checkbox' value='$value' id='roundedOne' name='$name'
$checked />
<label for='roundedOne'></label>
</div>";
}
$contents.= checkbox("name","value","1");
此外,您正在更改函数中$checked
参数的类型。强烈反对这种编码风格。尽量不要用这种方式更改变量的类型,这样会省去很多麻烦。
使用global $contents
或在函数return $contents
的末尾使用
函数返回了什么。返回函数中的字符串。或者使用$content作为全局变量,如oliverbj建议的
不确定我是否正确理解您的问题。您是否尝试过使用全局?
<?php
$contents = "string string string";
function checkbox($name, $value, $checked){
global $contents;
if($checked == 1){
$checked = "checked";
}else{
$checked ="";
}
$contents.="<div class='roundedOne'>
<input type='checkbox' value='$value' id='roundedOne' name='$name' $checked />
<label for='roundedOne'></label>
</div>";
}
$contents.=" ".checkbox("name","value","1")." ";
echo $contents;
?>
从函数返回$contents
的值。
通过这种方式,您可以在页面中获取$contents
的值。
比如
function checkbox($name, $value, $checked){
if($checked == 1){
$checked = "checked";
}else{
$checked ="";
}
$contents.="<div class='roundedOne'>
<input type='checkbox' value='$value' id='roundedOne' name='$name' $checked />
<label for='roundedOne'></label>
</div>";
return $contents;
}
您的函数没有返回值。
所以您没有从checkbox
函数得到任何响应。
只需要从函数中return $contents
,然后回显该结果即可。
function checkbox($name, $value, $checked){
if($checked == 1){
$checked = "checked";
}else{
$checked ="";
}
$contents.="<div class='roundedOne'>
<input type='checkbox' value='$value' id='roundedOne' name='$name' $checked />
<label for='roundedOne'></label>
</div>";
return $contents;
}
然后,
echo $contents;