...

これ - livedoor Blog

by user

on
Category: Documents
4

views

Report

Comments

Transcript

これ - livedoor Blog
PHP 入門 (基本編) メモ
1 PHP とは何か?
• PHP の概要
• 公式サイト
– http://php.net/
• 必要となる知識
– HTML, CSS
• レッスンの環境
2 はじめての PHP プログラム
• はじめての PHP プログラム
• PHP の開始タグ, 終了タグ
– 開始タグ: <?php
– 終了タグ: ?>
• コメントの書き方
– 単一行: //
– 複数行: /* ... */
3 変数を使ってみよう
• 変数とは何か
• 変数名の付け方
– $var
4 扱えるデータ型について
• 扱えるデータ型について
– 文字列
– 数値 (整数、小数)
1
– 論理値 (true, false)
– null
– 配列
– オブジェクト
– etc.
• var_dump 関数
– Dumps information about a variable
– void var_dump ( mixed $expression [, mixed $... ] )
5 定数を使ってみよう
• 定数の宣言
– define 関数
∗ Defines a named constant
∗ bool define ( string $name , mixed $value [, bool
$case_insensitive = false ] )
• 定数の使い方
– $は不要: echo name;
6 演算子を使ってみよう
• 代入演算子
– =
• 数値の演算
– 和: +
– 差: – 積: *
– 商: /
– 剰余: %
• 文字列の演算
– 連結演算子: . (dot)
• 単項演算子
– ++
– -• 代入を伴う演算子
– +=
– *=
– etc.
2
7 文字列についてみていこう
• 文字列の表現方法
– " (変数とエスケープ文字を展開する)
– ’ (変数とエスケープ文字を展開しない)
• 変数の展開
– $name = " taguchi ";
echo " hello $name" // outputs " hello taguchi "
echo ’hello $name ’ // outputs "hello $name "
• 特殊文字について
– 改行: \n
– タブ: \t
– バックスラッシュ: \\
– etc.
8 if で条件分岐をしてみよう (1)
• if 文による条件分岐
– if ( condition ) {
...
}
• 比較演算子
– < (less than)
– > (greater than)
– <= (less than or equal to)
– >= (greater than or equal to)
– == (equal to)
• 論理演算子
– && (AND)
– || (OR)
– ! (NOT)
9 if で条件分岐をしてみよう (2)
• if ... else ...
– if ( condition ) {
3
...
} else {
...
}
• if ... elseif ... else ...
– if ( condition ) {
...
} elseif ( condition ) {
...
} else {
...
}
• if 文の別の構文
– if ( condition ): ...
else: ...
endif ;
10 三項演算子を使ってみよう
• 三項演算子
– ( condition ) ? val1 : val2;
11 switch で条件分岐をしてみよう
• switch
– switch (var)
case val1:
...
break ;
case val2:
...
break ;
...
}
4
12 while でループを回してみよう
• while 文
– while ( condition ) {
...
}
• do ... while 文
– do {
...
} while ( condition );
13 for でループを回してみよう
• for 文
– for ( expr1 ; expr2; expr3) {
...
}
∗ The first expression (expr1) is evaluated (executed) once unconditionally at the beginning of the
loop.
∗ In the beginning of each iteration, expr2 is evaluated. If it evaluates to TRUE, the loop continues
and the nested statement(s) are executed. If it evaluates to FALSE, the execution of the loop ends.
∗ At the end of each iteration, expr3 is evaluated (executed).
14 ループを抜けてみよう
• break
– break ends execution of the current for, foreach, while, do-while or switch structure.
• continue
– continue is used within looping structures to skip the rest of the current loop iteration and continue
execution at the condition evaluation and then the beginning of the next iteration.
15 配列を使ってみよう
• 配列の作り方
– $a = array(val1, val2, ...);
• 要素へのアクセス
5
– 要素を取り出す: $a[i] \\ vali
– 要素を追加する: $a[] = val;
– 要素を変更する: $a[i] = val;
• 要素の削除
– unset($a[i]);
16 連想配列を使ってみよう
• 連想配列の作り方
– $a = array(key1=>val1, key2=>val2, ...);
• 要素へのアクセス
– 要素を取り出す: $a[keyi] \\ vali
– 要素を変更する: $a[keyi] = val;
– 要素を削除する: unset($a[keyi]);
17 配列をループさせてみよう
• foreach
– foreach ($a as $val) {
...
}
foreach ($a as $key => $val) {
...
}
18 関数を使ってみよう
• 関数の作成方法
– function f() {
...
}
• 関数の使い方
– f();
• 引数
– function f( $arg1 [= init1 ], $arg2 [= init2 ], ...) {
...
6
}
• 戻り値
– return
19 変数のスコープとは何か?
• 変数のスコープ
– {}内で定義された変数は{}内でのみ有効.
20 数学関数を使ってみよう
• ceil 関数
– Round fractions up
– float ceil ( float $value )
• floor 関数
– Round fractions down
– float floor ( float $value )
• round 関数
– Rounds a float
– float round ( float $val [, int $precision = 0 [, int $mode =
PHP_ROUND_HALF_UP ]] )
• pi 関数
– Get value of pi
– float pi ( void )
• rand 関数
– Generate a random integer
– int rand ( void )
int rand ( int $min , int $max )
– If called without the optional min, max arguments rand() returns a pseudo-random integer between
0 and getrandmax(). If you want a random number between 5 and 15 (inclusive), for example, use
rand(5, 15).
– On some platforms (such as Windows), getrandmax() is only 32767. If you require a range larger
than 32767, specifying min and max will allow you to create a range larger than this, or consider using
mt_rand() instead.
• mt_rand 関数
7
– Generate a better random value
– int mt_rand ( void )
int mt_rand ( int $min , int $max )
– Many random number generators of older libcs have dubious or unknown characteristics and are slow.
By default, PHP uses the libc random number generator with the rand() function. The mt_rand()
function is a drop-in replacement for this. It uses a random number generator with known characteristics using the Mersenne Twister, which will produce random numbers four times faster than what the
average libc rand() provides.
– If called without the optional min, max arguments mt_rand() returns a pseudo-random value between
0 and mt_getrandmax(). If you want a random number between 5 and 15 (inclusive), for example,
use mt_rand(5, 15).
21 文字列関数を使ってみよう
• strlen 関数
– Get string length
– int strlen ( string $string )
• strpos 関数
– Find the position of the first occurrence of a substring in a string
– mixed strpos ( string $haystack , mixed $needle [, int $offset = 0
] )
– Find the numeric position of the first occurrence of needle in the haystack string.
• substr 関数
– Return part of a string
– string substr ( string $string , int $start [, int $length ] )
• str_replace 関数
– Replace all occurrences of the search string with the replacement string
– mixed str_replace ( mixed $search , mixed $replace , mixed $subject
[, int & $count ] )
22 日本語を扱ってみよう
• mb_strlen 関数
– Get string length
– mixed mb_strlen ( string $str [, string $encoding =
mb_internal_encoding () ] )
8
• mb_strpos 関数
– Find position of first occurrence of string in a string
– int mb_strpos ( string $haystack , string $needle [, int $offset =
0 [, string $encoding = mb_internal_encoding () ]] )
• mb_substr 関数
– Get part of string
– string mb_substr ( string $str , int $start [, int $length = NULL
[, string $encoding = mb_internal_encoding () ]] )
23 書式を指定して文字列を表示する
• printf 関数
– Output a formatted string
– int printf ( string $format [, mixed $args [, mixed $... ]] )
• sprintf 関数
– Return a formatted string
– string sprintf ( string $format [, mixed $args [, mixed $... ]] )
• %s: 文字列に置換
• %d: 整数値に置換
• %f: 実数値に置換
24 配列関数を使ってみよう
• count 関数
– Count all elements in an array, or something in an object
– int count ( mixed $array_or_countable [, int $mode = COUNT_NORMAL ]
)
• sort 関数
– Sort an array
– bool sort ( array & $array [, int $sort_flags = SORT_REGULAR ] )
• in_array 関数
– Checks if a value exists in an array
– bool in_array ( mixed $needle , array $haystack [, bool $strict =
FALSE ] )
9
– Searches haystack for needle using loose comparison unless strict is set.
• implode 関数
– Join array elements with a string
– string implode ( string $glue , array $pieces )
• explode 関数
– Split a string by string
– array explode ( string $delimiter , string $string [, int $limit ]
)
25 日付/時間関数を使ってみよう (1)
• time 関数
– Return current Unix timestamp
– int time ( void )
• mktime 関数
– Get Unix timestamp for a date
– int mktime ([ int $hour = date ("H") [, int $minute = date ("i") [,
int $second = date ("s") [, int $month = date ("n") [, int $day =
date ("j") [, int $year = date ("Y") [, int $is_dst = -1 ]]]]]]] )
• strtotime 関数
– Parse about any English textual datetime description into a Unix timestamp
– int strtotime ( string $time [, int $now = time() ] )
– 例
∗ <?php
echo strtotime (" now ") , "\n";
echo strtotime ("10 September 2000") , "\n";
echo strtotime ("+1 day "), "\n";
echo strtotime ("+1 week "), "\n";
echo strtotime ("+1 week 2 days 4 hours 2 seconds ") , "\n";
echo strtotime (" next Thursday "), "\n";
echo strtotime (" last Monday ") , "\n";
?>
26 日付/時間関数を使ってみよう (2)
• date 関数
10
– Format a local time/date
– string date ( string $format [, int $timestamp = time() ] )
27 ファイルにデータを書き込もう (1)
• is_writable 関数
– Tells whether the filename is writable
– bool is_writable ( string $filename )
28 ファイルにデータを書き込もう (2)
• fopen 関数
– Opens file or URL
– resource fopen ( string $filename , string $mode [, bool
$use_include_path = false [, resource $context ]] )
– fopen のよく使われる書き方:
if (! fp = fopen ($filename , "a")) {
echo " Error opening file .";
exit;
}
• fwrite 関数
– Binary-safe file write
– int fwrite ( resource $handle , string $string [, int $length ] )
– fwrite のよく使われる書き方:
if ( fwrite ($fp , $string ) === false ) {
echo " Error writing file .";
exit;
}
29 ファイルにデータを書き込もう (3)
• fclose 関数
– Closes an open file pointer
– bool fclose ( resource $handle )
11
30 ファイルからデータを読み出そう (1)
• fread 関数
– Binary-safe file read
– string fread ( resource $handle , int $length )
– fread の決まり文句: fread($fp, filesize($filename))
31 ファイルからデータを読み出そう (2)
• file_get_contents 関数
– Reads entire file into a string
– string file_get_contents ( string $filename [, bool
$use_include_path = false [, resource $context [, int $offset =
-1 [, int $maxlen ]]]] )
• file 関数
– Reads entire file into an array
– array file ( string $filename [, int $flags = 0 [, resource
$context ]] )
32 フォームからのデータを受け取ろう
• フォームからの値の取得
– $_POST[name]
– $_GET[name]
• htmlspecialchars
– Convert special characters to HTML entities
– string htmlspecialchars ( string $string [, int $flags = ENT_COMPAT
| ENT_HTML401 [, string $encoding = "UTF -8" [, bool
$double_encode = true ]]] )
12
Fly UP