6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHPのチェックリスト

Posted at

OOPを少なめ

覚えて! OOPは常に遅い。 オブジェクトは作成、保存、破棄する必要があるから不適切にオブジェクトを使用しないことだ。 たとえば、ここに:

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

ただデーターをDBに保存するためにオブジェクトを使うのが勿体無い。そういう時は配列を使った方が良い。

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

ここでオブジェクトを使わずにDBに直接データーを保存できる。

絶対パス

ファイルの操作をする時は絶対パスを使うこと。

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

絶対パスを使わないとファイル検索の操作にリソースが無駄に使われてしまう。

クラスのコンスタント

defineよりクラスのconstの方が効率が良いからconstをなるべく使おう。

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

関数のない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'] = '変数の変換処理が発生しないから'
6
5
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?