PHP 함수를 기능으로 정의하여 이름을 붙여주고 그것을 만약 여러곳에 사용해야 한다면 이미 위에 정의를 해놓은 이름 함수가 있기 때문에 그 이름 함수로 쓰면 내가 원하는 기능이 나와서 코드가 길어질 이유가 없어진다.
<?php
function print_title() {
if(isset($_GET['id'])) {
echo $_GET['id'];
} else {
echo "Welcome";
} //id가 있다면 id값을 얻어오고 아니라면 Welcome을 보여주라는 print_title 함수이다.
}
function print_description() {
if(isset($_GET['id'])) {
echo file_get_contents("data/".$_GET['id']);
} else {
echo "hihihihi";
} //id가 있다면 data파일에 있는 id의 내용을 가져오고 아니라면 hihihihi를 보여주라는 print_description 함수이다.
}
function print_list() {
$list = scandir('./data');
$i = 0;
while($i < count($list)) {
if($list[$i] != '.') {
if($list[$i] != '..') {
echo "<a href=\"index.php?id=$list[$i]\"><li>$list[$i]</li></a>\n";
}
}
$i = $i + 1;
} //scandir은 폴더의 파일을 스캔하여 보여주는 함수이고 이 함수가 data 폴더를 읽으라고 정의하였다. 그리고 점 같은 부분은 나오지 않게 하고, 등등 이러한 기능을 print_list로 정의 하였다.
} //그리고 아래에 보이는 php 구문 안에 들어있는 부분이 여기에 쓴 함수를 쓰는 것이다.
?>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title><?php print_title();?></title>
</head>
<body>
<h1><a href="index.php">WEB</a></h1>
<ol>
<?php
print_list();
?>
<h2>
<?php print_title();?>
</h2>
</ol>
<h2>
<?php print_description();?>
</h2>
</body>
</html>
댓글