我要做的是创建一个可重用的画廊功能,如果需要,可以更改缩略图的布局。
我的问题是我的带有花括号变量的 $thumbLayout 字符串在包含在这样的函数中时不起作用,它仅在替换变量之后写入字符串时才起作用。
非常感谢任何帮助提出解决方案或更好的方法。
$thumbLayout = "<div class=\"customgallery\"><img src=\"{$thumbImgPath}\" width=\{$width}\" height=\"{$height}\" alt=\"{$imgName}\" /></div>";
function createImageGallery($galleryName,$db,$thumbLayout=''){
$imgno = 1;
//Page numbers//
if(isset($_GET['page']) && is_numeric($_GET['page'])) {
$page = $_GET['page'];
}elseif(isset($_POST['page']) && is_numeric($_POST['page'])) {
$page = $_POST['page'];
}else{
$page = 1;
}
$rowGallery = $db->query_first("SELECT gallery_id,num_cols,images_per_page FROM tblgallery WHERE gallery_name='$galleryName' AND show_gallery='y' LIMIT 1");
if($rowGallery!=false){
$recordsPerPage = $rowGallery['images_per_page'];
$numCol = $rowGallery['num_cols'];
$gallery = '<ul>';
$gallery_id = $rowGallery['gallery_id'];
$offset = ($page - 1) * $recordsPerPage;
$query = "SELECT * FROM tblimages WHERE group_id='$gallery_id' AND imgpath_thumb<>'' AND show_img='y' ORDER BY img_order";
$rs = $db->query("$query LIMIT $offset,$recordsPerPage");
foreach($rs as $row){
$largeImgPath = '/'.$row['imgpath_large'];
$imgName = $row['img_name'];
$thumbImgPath = '/'.$row['imgpath_thumb'];
if(($imgno>1) && (!is_float(($imgno-1)/$numCol))){
$li_class = 'class="newline"';
}elseif(($imgno>1) && (!is_float(($imgno)/$numCol))){
$li_class = 'class="last"';
}else{
$li_class = '';
}
list($width, $height) = getimagesize($row['imgpath_thumb']);
if($thumbLayout==''){
$gallery .= '<li '.$li_class.'><a href="'.$largeImgPath.'" class="popup" title="'.$imgName.'"><div class="gallery_imgbox"><img src="'.$thumbImgPath.'" width="'.$width.'" height="'.$height.'" alt="'.$imgName.'" /></div><span>'.$imgno.$imgName.'</span></a></li>';
}else{
$gallery .= '<li '.$li_class.'>'.$thumbLayout.'</li>';
}
$imgno++;
}
$gallery .= '</ul>';
}else{
//Gallery specified does not exist//
return 'Gallery does not exist';
}
return $gallery;
}
我认为这确实与 $thumbLayout 的位置有关。当在替换变量下方的函数内部时,它可以工作,但是当从函数外部包含时,它们不会被替换。好的,这是一个非常简单的例子:
$test1 = sprintf("My name is %s.",$name);
$test2 = "My name is {$name}.";
$test3 = "My name is ${name}.";
$test4 = "My name is $name .";
$test5 = "My name is <?= name ?>.";
$test6 = "My name is {{name}} .";
function showtest($test){
$name = "Bob";
echo $test;
}
showtest($test1); //Result: My name is .//
showtest($test2); //Result: My name is .//
showtest($test3); //Result: My name is .//
showtest($test4); //Result: My name is .//
showtest($test5); //Result: My name is .//
showtest($test6); //Result: My name is {{name}}.//
而这会起作用(但对我没有帮助)
function showtest2(){
$name = "Bob";
$test = "My name is {$name}.";
echo $test;
}
showtest2(); //Result: My name is Bob.//