Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/270.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在php中使用完整代码的括号_Php - Fatal编程技术网

如何在php中使用完整代码的括号

如何在php中使用完整代码的括号,php,Php,假设我在一个单独的php文件中有一个变量,即 $imgfile = "images/img.jpg"; <?php include("foo.html"); ?> 现在我有一个php文件,其中包括一个html或另一个php文件,即 $imgfile = "images/img.jpg"; <?php include("foo.html"); ?> 在foo.html中,我有以下代码 <html> <head> <title&g

假设我在一个单独的php文件中有一个变量,即

$imgfile = "images/img.jpg";
<?php 
include("foo.html");
?>
现在我有一个php文件,其中包括一个html或另一个php文件,即

$imgfile = "images/img.jpg";
<?php 
include("foo.html");
?>

在foo.html中,我有以下代码

<html>
<head>
<title>foo site</title>
</head>
<body>
<img src="<?php echo $imgfile; ?>">

富网站
">
这是可行的,但我包括$imgfile多次,所以我不想键入
一次又一次..我只需键入
{$imgfile}就可以看到许多包含此类文件的脚本
但我不知道如何使用它,请告诉我如何使用这种格式..???

我认为Smarty,一个模板引擎,是您需要的。请参阅此链接:

PHP已经是一个模板引擎了。
因此,
echo
语句的形式较短,特别是出于此目的:

<?=$imgfile?>

相当短,与
{$imgfile}

请注意,要使用括号,您必须为循环、条件和其他语句设计替代方案,这将使您的生活复杂化。 使用PHP作为模板时,您将能够使用内置的PHP操作符,如
foreach
if
或include

因此,最好坚持
语法


只需确保已启用
short\u open\u tags
设置

为了实现此行为,您应该使用模板引擎,或者编写自己的解释器,用适当的值替换这些表达式

e、 g


这里有三种选择

1) 将
“>
分配给较短的字符串

 $a = "<img src='$imgfile'>";

3) 使用模板引擎,如或smarty。(首选方法

很抱歉,我读了你的问题,但我认为它不起作用,因为你把它放在了*.html文件中。这是行不通的。你能进一步说明你在寻找什么吗?noop我把html文件包括在php文件中,所以它是工作的3个方法中的2个有严重的设计缺陷。还有刚才提到的第三个。这是一个好的答案吗?尽管第一种方法有输入错误,但它破坏了模板的整个概念。所有html代码都应该出现在模板中。通过向控制器代码中添加HTML,您可以在业务逻辑和表示之间拆分HTML,使其比以前更糟糕。在第二个例子中,没有任何理由将文本文件解释为PHP代码,捕获缓冲区,然后进行处理。您只需从磁盘读取并处理它。
 <?php echo ob_start('myReplacementCallback') ?>
 <html>
 <head>
 <title>foo site</title>
 </head>
 <body>
 {{imgfile}}
 <?php ob_end_flush (); ?>
function myReplacementCallback($contents) {
    $replacements = array(
        '{{imgfile}}' => "<img src='/path/to/image'>",
    );

    return str_replace(array_keys($replacements), $replacements, $contents);
}