메뉴 건너뛰기

프로그램언어

조회 수 268 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄

#정리할 내용

- 프로그램에서 함수를 정의하고 호출하기

- 필수 인수가 있는 함수 정의하기

- 선택적 인수가 있는 함수 정의하기

- 함수에서 값 반환하기

- 변수 영역에 대한 이해

- 함수 내부에서 전역 변수 사용하기

- 형 선언에 대한 이해

- 인수 형 선언 사용하기

- 반환 형 선언 사용하기

- PHP 코드를 여러 파일에 나눠 관리하기

 

 

 

#코드 정리

 

- 프로그램에서 함수를 정의하고 호출하기

0

<?php
function page_header() {
print '<html><head><title>저의 홈페이지에 오신 것을 환영합니다.</title></head>';
print '<body bgcolor="#ffffff">';
}
 
page_header();
print "어서오세요, $user 님.";
page_footer();
 
function page_footer() {
print '<hr>방문해주셔서 감사합니다.';
print '</body></html>';
}

 

1

<?php
function countdown($top) {
while ($top > 0) {
print "$top..";
$top--;
}
print "펑!\n";
}
 
$counter = 5;
countdown($counter);
print "counter의 값: $counter";
 
//출력
 
5..4..3..2..1..펑! counter의 값: 5
 

 

2

<?php
function page_header2($color) {
print '<html><head><title>저의 홈페이지에 오신 것을 환영합니다.</title></head>';
print '<body bgcolor="#' . $color . '">';
}
 
page_header2('cc00cc');

 

3

<?php
function page_header4($color, $title) {
print '<html><head><title>' . $title . '에 오신 것을 환영합니다.</title></head>';
print '<body bgcolor="#' . $color . '">';
}
 
page_header4('66cc66','저의 홈페이지');

 

 

- 필수 인수가 있는 함수 정의하기

<?php
function countdown(int $top) {
while ($top > 0) {
print "$top..";
$top--;
}
print "펑!\n";
}

 

//에러가 난다. 인수 값으로 int 만들어가야됨
countdown("grunt");

 

//오류

PHP Fatal error:  Uncaught TypeError: Argument 1 passed to countdown() must be of the type integer, string given, called in {{d}}decl-error.php on line 2 and defined in {{d}}countdown.php:2

Stack trace:

#0 {{d}}decl-error.php(2): countdown('grunt')

#1 {main}

 

  thrown in {{d}}countdown.php on line 2

 

 

- 선택적 인수가 있는 함수 정의하기

1

<?php
function page_header3($color = 'cc3399') {
print '<html><head><title> 저의 홈페이지에 오신 것을 환영합니다.</title></head>';
print '<body bgcolor="#' . $color . '">';
}

 

2

<?php
// 선택적 인수가 하나일 때. 마지막 인수여야 한다.
function page_header5($color, $title, $header = '어서오세요') {
print '<html><head><title>' . $title . '에 오신 것을 환영합니다.</title></head>';
print '<body bgcolor="#' . $color . '">';
print "<h1>$header</h1>";
}
// 올바른 호출 방법
page_header5('66cc99','저의 멋진 홈페이지'); // $header의 기본값을 사용한다.
page_header5('66cc99','저의 멋진 홈페이지','홈페이지 최고에요!'); // 기본값을 사용하지 않는다.
 
// 선택적 인수가 두 개일 때. 마지막 두 인수에 지정해야 한다.
function page_header6($color, $title = '저의 홈페이지', $header = '어서오세요') {
print '<html><head><title>' . $title . '에 오신 것을 환영합니다.</title></head>';
print '<body bgcolor="#' . $color . '">';
print "<h1>$header</h1>";
}
// 올바른 호출 방법
page_header6('66cc99'); // $title과 $header의 기본값을 사용한다.
page_header6('66cc99','저의 멋진 홈페이지 '); // $header의 기본값을 사용한다.
page_header6('66cc99','저의 멋진 홈페이지 ','홈페이지 최고에요!'); // 기본값을 사용하지 않는다.
 
// 인수가 모두 선택적일 때
function page_header7($color = '336699', $title = '저의 홈페이지', $header = '어서오세요') {
print '<html><head><title>' . $title . '에 오신 것을 환영합니다.</title></head>';
print '<body bgcolor="#' . $color . '">';
print "<h1>$header</h1>";
}
 
// 올바른 호출 방법
page_header7(); // 모두 기본값을 사용한다.
page_header7('66cc99'); // $title과 $header의 기본값을 사용한다.
page_header7('66cc99','저의 멋진 홈페이지'); // $header의 기본값을 사용한다.
page_header7('66cc99','저의 멋진 홈페이지','홈페이지 최고에요!'); // 기본값을 사용하지 않는다.

 

- 함수에서 값 반환하기 (:return value 타입을 float로 지정했다)

<?php
 
function restaurant_check($meal, $tax, $tip): float {
$tax_amount = $meal * ($tax / 100);
$tip_amount = $meal * ($tip / 100);
$total_amount = $meal + $tax_amount + $tip_amount;
 
return $total_amount;
}
 
restaurant_check(100,7,20);

 

- 기본값에 변수를 지정할 수 없다.

$my_color = '#000000';
 
// 잘못된 구문. 기본값에 변수를 지정할 수 없다.
function page_header_bad($color = $my_color) {
print '<html><head><title>저의 홈페이지에 오신 것을 환영합니다.</title></head>';
print '<body bgcolor="#' . $color . '">';
}

 

- 변수 영역에 대한 이

0

<?php
$dinner = '갑오징어 카레';
 
function vegetarian_dinner() {
print "저녁 메뉴는 $dinner, 또는 ";
$dinner = '완두싹 볶음';
print $dinner;
print "입니다.\n";
}
 
function kosher_dinner() {
print "저녁 메뉴는 $dinner, 또는 ";
$dinner = '궁보계정';
print $dinner;
print "입니다.\n";
}
 
print "채식주의식 ";
vegetarian_dinner();
print "유태인식 ";
kosher_dinner();
print "일반 저녁 메뉴는 $dinner 입니다.";
 
//출력
채식주의식 저녁 메뉴는 , 또는 완두싹 볶음입니다. 유태인식 저녁 메뉴는 , 또는 궁보계정입니다. 일반 저녁 메뉴는 갑오징어 카레 입니다.

 

1

<?php
$dinner = '갑오징어 카레';
 
function vegetarian_dinner() {
global $dinner;
print "저녁 메뉴는 $dinner 였습니다만, 지금은 ";
$dinner = '완두싹 볶음';
print $dinner;
print "입니다.\n";
}
 
print "일반 저녁 메뉴는 $dinner 입니다.\n";
vegetarian_dinner();
print "일반 저녁 메뉴는 $dinner 입니다.";
 
//
일반 저녁 메뉴는 갑오징어 카레 입니다. 저녁 메뉴는 갑오징어 카레 였습니다만, 지금은 완두싹 볶음입니다. 일반 저녁 메뉴는 완두싹 볶음 입니다.

 

- 함수 내부에서 전역 변수 사용하기

0

<?php
$dinner = '갑오징어 카레';
 
function macrobiotic_dinner() {
$dinner = "모듬 채소";
print "저녁 메뉴는 $dinner 입니다.";
// 해산물의 유혹에 굴복하고 말았음
print " 하지만 저는 ";
print $GLOBALS['dinner'];
print "를 먹겠어요.\n";
}
 
macrobiotic_dinner();
print "일반 저녁 메뉴: $dinner";
 
//
저녁 메뉴는 모듬 채소 입니다. 하지만 저는 갑오징어 카레를 먹겠어요. 일반 저녁 메뉴: 갑오징어 카레

 

1

<?php
$dinner = '갑오징어 카레';
 
function hungry_dinner() {
$GLOBALS['dinner'] .= ' 그리고 바싹 익힌 토란';
}
 
print "일반 저녁 메뉴는 $dinner 입니다.";
print "\n";
hungry_dinner();
print "저녁 특선 메뉴는 $dinner 입니다.";
 
//출력
일반 저녁 메뉴는 갑오징어 카레 입니다. 저녁 특선 메뉴는 갑오징어 카레 그리고 바싹 익힌 토란 입니다.
 

 

- 형 선언에 대한 이해 / int로 형선언

<?php
function countdown(int $top) {
while ($top > 0) {
print "$top..";
$top--;
}
print "펑!\n";
}

 

//에러가 난다. 인수 값으로 int 만들어가야됨
countdown("grunt");

 

 

- 반환 형 선언 사용하기

<?php
 
function restaurant_check($meal, $tax, $tip): float {
$tax_amount = $meal * ($tax / 100);
$tip_amount = $meal * ($tip / 100);
$total_amount = $meal + $tax_amount + $tip_amount;
 
return $total_amount;
}
 
restaurant_check(100,7,20);
 

 

- 반복문과 함수 같이 사용하기

 

<?php
function restaurant_check($meal, $tax, $tip) {
$tax_amount = $meal * ($tax / 100);
$tip_amount = $meal * ($tip / 100);
return $meal + $tax_amount + $tip_amount;
}
 
$cash_on_hand = 31;
$meal = 25;
$tax = 10;
$tip = 10;
 
while(($cost = restaurant_check($meal,$tax,$tip)) < $cash_on_hand) {
$tip++;
print "팁으로 $tip% ($cost) 정도는 낼 수 있지\n";
}
?>
 
//팁으로 11% (30) 정도는 낼 수 있지
팁으로 12% (30.25) 정도는 낼 수 있지 팁으로 13% (30.5) 정도는 낼 수 있지 팁으로 14% (30.75) 정도는 낼 수 있지

 

- 함수와 if문

0

<?php
// 음식가격은 $15.22, 부가세는 8.25%, 팁은 15%일 때 총금액 구하기
$total = restaurant_check(15.22, 8.25, 15);
 
print '수중에 현금이 총 $20이니까...';
if ($total > 20) {
print "신용카드로 결제해야 돼.";
} else {
print "현금으로 낼 수 있어.";
}
//결과
//수중에 현금이 총 $20이니까...현금으로 낼 수 있어.

 

 

1

<?php
function complete_bill($meal, $tax, $tip, $cash_on_hand) {
$tax_amount = $meal * ($tax / 100);
$tip_amount = $meal * ($tip / 100);
$total_amount = $meal + $tax_amount + $tip_amount;
if ($total_amount > $cash_on_hand) {
// 계산금액이 가진돈보다 많음
return false;
} else {
// 이정도는 낼 수 있음
return $total_amount;
}
}
 
if ($total = complete_bill(15.22, 8.25, 15, 20)) {
print "$total 정도면 딱 좋지.";
} else {
print "제가 돈이 없어서 그러는데, 대신 접시라도 닦으면 안될까요?";
}
 
//결과
18.75865 정도면 딱 좋지.

 

 

- 함수와 배열 (리턴값으로 배열을 사용할수 있다.)

<?php
function restaurant_check2($meal, $tax, $tip) {
$tax_amount = $meal * ($tax / 100);
$tip_amount = $meal * ($tip / 100);
$total_notip = $meal + $tax_amount;
$total_tip = $meal + $tax_amount + $tip_amount;
 
return array($total_notip, $total_tip);
}
 
 
$totals = restaurant_check2(15.22, 8.25, 15);
 
if ($totals[0] < 20) {
print '팁을 제외한 총금액이 $20보다 적음.';
}
 
if ($totals[1] < 20) {
print '팁을 포함한 총금액이 $20보다 적음.';
}
 
//결과
팁을 제외한 총금액이 $20보다 적음.팁을 포함한 총금액이 $20보다 적음.

 

- 배열의 리턴값을 또다른 함수의 인자 값으로 넣을 수 있다.

0

function restaurant_check($meal, $tax, $tip) {
$tax_amount = $meal * ($tax / 100);
$tip_amount = $meal * ($tip / 100);
$total_amount = $meal + $tax_amount + $tip_amount;
 
return $total_amount;
}
 
 
function payment_method($cash_on_hand, $amount) {
if ($amount > $cash_on_hand) {
return '신용카드';
} else {
return '현금';
}
}
 
$total = restaurant_check(15.22, 8.25, 15);
 
$method = payment_method(20, $total);
print '결제 방법은 ' . $method . '입니다';
 
//결과
결제 방법은 현금입니다
 
 
 
if (restaurant_check(15.22, 8.25, 15) < 20) {
print '$20가 안되니, 현금으로 내야지.';
} else {
print '너무 비싼데, 신용카드를 써야겠어.';
}
 
//결과
$20가 안되니, 현금으로 내야지.

 

1

function can_pay_cash($cash_on_hand, $amount) {
if ($amount > $cash_on_hand) {
return false;
} else {
return true;
}
}
 
$total = restaurant_check(15.22,8.25,15);
if (can_pay_cash(20, $total)) {
print "현금으로 낼 수 있어.";
} else {
print "신용카드를 써야겠네.";
}
//결과
현금으로 낼 수 있어.

 

- PHP 코드를 여러 파일에 나눠 관리하기

restaurant-functions.php
 
<?php
 
function restaurant_check($meal, $tax, $tip) {
$tax_amount = $meal * ($tax / 100);
$tip_amount = $meal * ($tip / 100);
$total_amount = $meal + $tax_amount + $tip_amount;
 
return $total_amount;
}
 
function payment_method($cash_on_hand, $amount) {
if ($amount > $cash_on_hand) {
return '신용카드';
} else {
return '현금';
}
}
 
?>

 

restaurant-use-funcs.php

<?php
 
require 'restaurant-functions.php';
 
/* 음식가격 $25, 더하기 부가세 8.875%, 더하기 팁 20% */
$total_bill = restaurant_check(25, 8.875, 20);
 
/* 가진돈 $30 */
$cash = 30;
 
print "결제 방법은 " . payment_method($cash, $total_bill);

//결과

결제 방법은 신용카드

 

 


List of Articles
번호 제목 날짜 조회 수
340 환경변수 HTTP_USER_AGENT를 이용해서 스마트 기기 분류하기 2016.09.21 25959
339 확장자 추출 하기 2021.03.26 309
338 홈페이지 귀퉁이에 붙이는 공지창 file 2015.04.06 25426
337 헤더이용 다운로드 받을시 바로열기부분 소스 2018.07.24 7320
336 해당하는 날짜가 그달의 몇주째인지 계산 2014.02.27 26351
335 함수이름을 변수로 사용하기, 매개변수 없는 함수에 매개변수 넣기 2021.03.26 747
334 한글줄바꾸기 또는 utf-8 wordwrap 2014.04.12 26546
333 한글자르기 substr 2015.04.14 25198
332 한글이 깨져서 나올 때 - iconv 2018.08.29 3933
331 필드값 저장 2014.02.27 24276
330 프레임 사이트에서 새로고침(F5) 할때 초기화면으로 이동하지 않음 2019.01.08 1280
329 폴더에 사진올려놓고 리스트자동으로 만들기 2019.01.08 1302
328 폴더 용량 체크 2023.01.12 218
327 포트체크 방법 2019.01.16 1288
326 페이지 로딩 시간 측정 2014.02.27 26041
325 파일을 변수에 담기(ob_start를 이용한 방법) 2021.03.26 674
324 파일업로드 2017.02.19 19352
323 파일시스템, 폼 파일업로드 관련 함수 2017.03.27 21681
322 파일 확장자 비교 2016.12.23 21970
321 파일 종류에 따른 아이콘표시하기 함수 2019.01.16 1421
Board Pagination Prev 1 2 3 4 5 6 7 8 9 10 ... 17 Next
/ 17

하단 정보를 입력할 수 있습니다

© k2s0o1d4e0s2i1g5n. All Rights Reserved