我有一个功能,它将扫描目录并从目录中获取php文件,然后相同的php文件将匹配内容并获取模板名称。由于一些奇怪的原因,传递给函数的变量不会被开始识别。
变量 $ selected 无法正常工作。我试过很少想像
更多信息
变量仅在这行代码
之前使用时才有效$indir = array_filter($files, function($item){
当我删除全局$ selected 时,我收到了此错误消息
Notice: Undefined variable: selected in
这就是我目前的
/* Scan's the theme directory and gets the PHP files which has Template named defined (Template: Your Template Name)*/
function get_theme_templates($name = "template", $noparent = true, $selected = "Works!"){
echo "<select class=\"fs12 template\" id=\"template\" name=\"".$name."\">";
if($noparent){ echo "<option value=\"-1\">No Parent</option>";}
$dir = dirname(dirname(dirname(__FILE__))) . '/system/themes/';
$files = scandir($dir);
$indir = array_filter($files, function($item){
if($item[0] !== '.'){
if( get_extension($item) == "php"){
global $dir;
$search = "Template: ";
@header('Content-Type: text/plain');
$contents = file_get_contents(dirname(dirname(dirname(__FILE__))) . '/system/themes/' . $item);
$pattern = preg_quote($search, '/');
$pattern = "/^.*$pattern.*\$/m";
if(preg_match_all($pattern, $contents, $matches)){
$template = implode("\n", $matches[0]);
$template_sanitize = array("Template:", "/* ", " */");
$template = str_replace($template_sanitize, "", $template);
$template = trim($template);
if( trim($template) == trim($selected) ){
echo "<option value=\"" . $template . $selected . "\" selected=\"selected\">" . $template . "</option>";
} else {
echo "<option value=\"" . $template . $selected . "\">" . $template . "</option>";
}
}
}
}
});
echo "</select>";
}
答案 0 :(得分:0)
在调用函数之前:
$selected; // Undefined.
在功能开始时:
$selected = "Works!";
然后你覆盖它
global $selected;
使其内容未定义。不要覆盖该值并转储它的内容以检查它的实际内容。
答案 1 :(得分:0)
参见变量范围: http://www.php.net/manual/en/language.variables.scope.php
$selected = 'global';
function get_theme_templates(){
$selected = 'get_theme_templates';
$indir = array_filter($files, function($item){
print_r($selected);
});
}
PHP的行为与JS不同。 array_filter代码块中没有选择$。如果在此函数中执行全局$选择,它将获取全局值,而不是get_theme_templates()内部的值。