重复使用网页中的单词/短语
I use a standard document for all my clients, however want to change their business name and address in several places, so to save time copy and pasting, I want to find a way to reuse words and phrases:
One approach to reusing code that I have found is:
<html>
<body>
<?php
$color = "red";
$second = "blue";
?>
<p>Roses are <?=$color?></p>
<?=$second?>
<p><b>Note:</b> The shortcut syntax only works with the short_open_tag configuration setting enabled.</p>
</body>
</html>
However, is this best practice? or is there a more standard way to use PHP than this?
The source I got this from said: Shortcut syntax (will only work with the short_open_tag configuration setting enabled)
我为所有客户使用标准文档,但是想在几个地方更改他们的公司名称和地址,所以 为了节省复制和粘贴的时间,我想找到一种方法来重用单词和短语: p>
重用我找到的代码的一种方法是: p>
但是, 这是最佳做法吗? 或者有更标准的方法来使用PHP吗? p>
我得到的源代码来自:快捷语法(仅适用于启用了short_open_tag配置设置) p> \ n div>&lt; html&gt;
&lt; body&gt;
&lt;?php
$ color =“red”;
$ second =“blue”;
?&gt;
&lt; p&gt; ;玫瑰是&lt;?= $ color?&gt;&lt; / p&gt;
&lt;?= $ second?&gt;
&lt; p&gt;&lt; b&gt;注意:&lt; / b&gt; 快捷语法仅适用于启用了short_open_tag配置设置。&lt; / p&gt;
&lt; / body&gt;
&lt; / html&gt;
code> pre>
Making repetitive phrases into variables is a good idea. If you are using them across multiple pages you can even abstract them to another file and then include it on each page like this:
config.php
<?php
$name = "Business Name";
$address = "Address";
index.php
<?php
include config.php;
?>
<html>
<body>
<p><?php echo $name; ?>
</body>
</html>
It's a good idea to use full <?php ?>
tags rather than <? ?>
as this is the short form and is not always configured to work out of the box on each installation of php!
For PHP compatibility (and sanity reasons) most people use:
<?php echo $colors; ?>
Some websites who host PHP disable short tags (or at least most I've used). So, generally speaking, using the longer version that is more compatible is better.
A lot of the reason why some webhosts support it and others don't is in the history of it being enabled and disabled. Before 5.4 it was disabled by default, in 5.4+ it is default enabled.
Now, let's do a small table of pros and cons:
Pros:
- You save your hands from 8 extra characters of arthritis.
Cons:
- Your website has potential compatibility issues.
That was a bit of a joke, but using the longer version is better.
An aside, if you ever want to disable have variables span multiple webpages you can put in a sperate file like:
variables.php
<?php
$color = "red";
$mainSettings = Array(
"color" => "red"
);
?>
And then all you have to do on each php page is include this file like:
<?php
include("variables.php");
echo $mainSettings["color"];
echo $color;
?>
Note: to avoid conflicting with other global PHP variables, I would highly recommend using a PHP associated array to store all of your cross-page variables in.
you can use a function
, include
it in you script, pass some user info or company and return
a string
or html
or even write the entire page, whatever you are comfortable with.