PHP的检查清单

减少使用面向对象编程 (OOP)

记住!面向对象编程(OOP)总是慢的。这是因为对象需要创建、存储和销毁,所以不要不恰当地使用对象。例如,在这里:

$post = new Post();
$post->set_title($_GET['title']);
$post->set_description($_GET['description']);
$post->save();

只是为了将数据存储到数据库中,使用对象是浪费的。这种情况下使用数组更好。

mysql::insert(['title' => $_GET['title'], 'description' => $_GET['description']]);

在这里,可以直接将数据保存在数据库中而无需使用对象。

绝对路径

操作文件时请使用绝对路径。

/*
include 'file.php';
file_get_contents('dir/data.txt');
*/
include '/var/www/file.php';
file_get_contents('/var/www/dir/data.txt');

如果不使用绝对路径进行文件搜索操作,会浪费资源。

班级的恒定

由于const在效率上优于define,因此尽量使用const。

// define('MAX_POSTS_PER_PAGE', 10);
class posts {
    const PER_PAGE = 10;
    ...
}

没有函数的for循环 de for

// for ($i = 0; $i < count($list); $i++) ...

$count = count($list);
for ($i = 0; $i < $count; $i++) ...

如果将函数放入for循环中,那么该函数会在每次迭代中执行。

正则表达式的速度很慢。

preg_match('/example/ui', $post['title']);
strpos($post['title'], 'example');

最好使用标准函数来操作字符串,而不是正则表达式。

单引号

在PHP中,如果给字符串加上双引号,就会导致变量被转换。因此,在没有变量的情况下,请务必使用单引号。

// $post["title"] = "なぜ?";
$post['title'] = '変数の変換処理が発生しないから'