哪种格式正确?我还不知道如何缩进PHP代码。我觉得Set 2是正确的,但我还不知道。
设置1
$connection = mysqli_connect('localhost', 'ijdbuser', 'ijdbpw');
if (!$connection)
{
$error = 'Unable to connect to the database server.';
include 'error.html.php';
exit();
}
if (!mysqli_set_charset($connection, 'utf8'))
{
$output = 'Unable to set database connection encoding.';
include 'output.html.php';
exit();
}
if (!mysqli_select_db($connection 'ijdb'))
{
$error = 'Unable to locate the joke database.';
include 'error.html.php';
exit();
}
$result = mysqli_query($connection, "SELECT joketext FROM joke");
if (!$result)
{
$error = 'Error fetching jokes: ' . mysqli_error($connection
);
include 'error.html.php';
exit();
}
while ($row = mysqli_fetch_array($result))
{
$jokes[] = $row['joketext'];
}
include 'jokes.html.php';
?>
设置2
$connection = mysqli_connect('localhost', 'ijdbuser', 'ijdbpw');
if (!$connection)
{
$error = 'Unable to connect to the database server.';
include 'error.html.php';
exit();
}
if (!mysqli_set_charset($connection, 'utf8'))
{
$output = 'Unable to set database connection encoding.';
include 'output.html.php';
exit();
}
if (!mysqli_select_db($connection 'ijdb'))
{
$error = 'Unable to locate the joke database.';
include 'error.html.php';
exit();
}
$result = mysqli_query($connection, "SELECT joketext FROM joke");
if (!$result)
{
$error = 'Error fetching jokes: ' . mysqli_error($connection
);
include 'error.html.php';
exit();
}
while ($row = mysqli_fetch_array($result))
{
$jokes[] = $row['joketext'];
}
include 'jokes.html.php';
?>
答案 0 :(得分:2)
没有"对" 或"错误" 格式化,而不是真的。只要保持一致,选择你最喜欢的风格。但是,有PHP-FIG这样的事情。他们提出的编码风格是最常用的编码风格,而且几乎所有主要的开源项目都会使用它。
就个人而言,我尝试尽可能多地订阅他们的编码标准,尽管我倾向于选择allman风格的括号(if ()\n{\n
)。我想我几年前给他们发了一份公关,以便允许这种缩进方式,但它被拒绝了(主要是为了避免因冲突空白的合并冲突,所以我明白他们来自哪里)。
答案 1 :(得分:1)
PSR - 这些不是类似法律的规则,但如果你遵循这些规则就不会错。
答案 2 :(得分:1)
请使用此。 PHP美化也可以帮助很多。
<?php
$connection = mysqli_connect('localhost', 'ijdbuser', 'ijdbpw');
if (!$connection)
{
$error = 'Unable to connect to the database server.';
include 'error.html.php';
exit();
}
if (!mysqli_set_charset($connection, 'utf8'))
{
$output = 'Unable to set database connection encoding.';
include 'output.html.php';
exit();
}
if (!mysqli_select_db($connection'ijdb'))
{
$error = 'Unable to locate the joke database.';
include 'error.html.php';
exit();
}
$result = mysqli_query($connection, "SELECT joketext FROM joke");
if (!$result)
{
$error = 'Error fetching jokes: ' . mysqli_error($connection);
include 'error.html.php';
exit();
}
while ($row = mysqli_fetch_array($result))
{
$jokes[] = $row['joketext'];
}
include 'jokes.html.php';
?>
答案 3 :(得分:1)
似乎更具可读性。是的,清洁,可读性,清晰,易于维护是一些因素,而不仅仅是标准。查看Proposed Standards Recommendation (PSR),还可以查看不同的php 开源框架及其样式指南或github上的编码约定或贡献样式指南。
例如:
我选择项目的团队和社区/组织最适合的......流体。
也将提供帮助:(Clean Code by Robert C.Martin)
希望这有帮助。