変数とデータ型
変数
- 変数の宣言と代入
- $変数名 = 値;
- 変数の出力
-
print '文字列'.変数名.'文字列;
文字列の結合は.(ドット)
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8" />
<title>変数1</title>
</head>
<body>
<?php
$str = 'abc';
print '<p>文字列str='.$str.'です</p>';
?>
</body>
</html>
コーテーションマーク
- print "(ダブルコーテーション) $変数名";
- 変数の値が表示される(「変数が展開される」)
- print '(シングルコーテーション) $変数名';
- $変数名を文字列と見なして出力される
- エスケープ文字
-
htmlのダブルコーテーションとPHPのダブルコーテーションがバッティングするときにはhtmlのダブルコーテーションの前にエスケープ文字(\)を置く
PHPがわでシングルコーテーションを使うときには問題ない
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8" />
<title>ダブルコーテーションとシングルコーテーション</title>
</head>
<body>
<h1>ダブルコーテーションとシングルコーテーション</h1>
<?php
$str = '文字列';
print '<p class="test">'.$str.'</p>';
print '<p class="test">$str</p>';
print "<p class=\"test\">$str</p>";
?>
</body>
</html>
データの型
<?php
date_default_timezone_set('Asia/Tokyo');
$today_date = date("d"); //文字列型
$today_month = date("m"); //文字列型
$today_year = date("Y"); //文字列型
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8" />
<title>データの型</title>
</head>
<body>
<?php
print '<p>今日は'.$today_year.'年'.$today_month.'月'.$today_date.'日です(today_monthはこの段階では文字列型)</p>';
print '<p>一ヶ月後は'.$today_year.'年'.($today_month + 1).'月'.$today_date.'日です(today_monthは数値型に変換される)</p>';
?>
<!--上記計算は暫定的なもので正しいものではない(12月の次は13月になる)-->
</body>
</html>
- 弱いデータ型
- PHPでは変数のデータ型は自動的に変換されるので余り意識しなくても使える(Excelに近い)。
- 強いデータ型
- 変数がどのデータ型なのかをあらかじめ宣言して使用する必要がある言語もある(Accessに近い)。