>  기사  >  백엔드 개발  >  PHP의 함수

PHP의 함수

王林
王林원래의
2024-08-29 12:46:08366검색

PHP에서는 내장 함수, 사용자 정의 함수 등 다양한 함수를 사용합니다. 각각의 모든 기능에는 고유한 기능과 속성이 있습니다. 함수는 필요한 곳 ​​어디에서나 코드에서 여러 번 사용할 수 있는 프로그램에 작성된 명령문 세트입니다. 함수 내부에 작성된 명령문을 실행하려면 함수 호출이 필요합니다. 하나 이상의 입력을 매개변수로 가져와 처리하고 값을 반환하는 코드 조각입니다. 프로그래머는 함수를 생성한 다음 필요할 때마다 프로그램에서 해당 함수를 호출하기만 하면 됩니다.

광고 이 카테고리에서 인기 있는 강좌 PHP 개발자 - 전문 분야 | 8개 코스 시리즈 | 3가지 모의고사

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

PHP의 함수 종류

PHP에서는 프로그래머가 주로 두 가지 함수를 사용합니다. 그들은:

1. 사용자 정의

이러한 함수는 개발자나 프로그래머가 자신의 코드 논리를 실행해야 할 때 사용됩니다. 이러한 함수는 function 키워드를 사용하여 정의되며 함수 내부에는 함수 호출이 발생할 때 이를 실행하기 위한 일련의 명령문이 작성됩니다. functionname()과 같은 함수를 호출하기만 하면 함수 호출이 가능하며, 함수가 실행됩니다.

2. 내장

이러한 함수는 내장된 라이브러리 함수를 제공합니다. PHP는 설치 패키지 자체에 이러한 기능을 제공하여 이 언어를 더욱 강력하고 유용하게 만듭니다. 함수의 속성을 사용하려면 원하는 결과를 가져오는 데 필요할 때마다 함수를 호출하기만 하면 됩니다.

PHP에는 날짜, 숫자, 문자열 등 다양한 내장 함수가 사용됩니다.

  • 문자열 함수: 이 함수에는 문자열 작업을 위해 PHP에 미리 정의된 기능이 있습니다. PHP에는 strpos(), strncmp(), strrev(), strlen(),
  • 등 다양한 문자열 함수가 있습니다.
  • 날짜 함수: 이러한 함수는 PHP에서 사전 정의된 기능으로, 형식은 사람이 읽을 수 있는 형식인 UNIX 날짜 및 시간입니다.
  • 숫자 함수: 이 함수에는 숫자 연산에 사용되는 PHP에서 제공하는 사전 정의된 자체 논리가 있습니다. 결과는 부울 형식이나 숫자 형식으로 반환됩니다. 숫자 함수에는 is_number(), number_format(), round() 등이 포함됩니다.

PHP에서 함수를 사용해야 하는 이유는 무엇인가요?

다음은 PHP에서 함수를 사용해야 하는 이유를 설명합니다.

  • 재사용성: 모든 프로그래밍 언어에서는 여러 번 작성해야 하는 코드 줄을 줄이기 위해 함수가 사용됩니다. 이렇게 하면 개발자나 프로그래머의 시간과 노력이 줄어듭니다. 공통 코드를 여러 영역에서 사용해야 하는 경우 이를 함수에 포함하고 필요할 때 언제 어디서나 호출할 수 있습니다. 이는 동일한 프로그램에서 함수를 호출하거나 일부 다른 프로그램에서 사용함으로써 달성할 수 있습니다.
  • 더 쉬운 오류 감지: 코드를 일괄적으로 작성하지 않고 분할하거나 기능별로 나누어 작성하기 때문에 오류가 발생하면 쉽게 감지하고 오류를 빠르고 쉽게 수정할 수 있습니다.
  • 간편한 유지 관리: 함수는 프로그램에서 사용되기 때문에 어떤 함수나 코드 한 줄을 변경해야 할 경우 함수 내에서 쉽게 변경할 수 있으며 변경 사항이 반영됩니다. 그래서 어디서나 관리가 쉽습니다.

PHP에서 함수는 어떻게 사용되나요?

앞서 논의한 것처럼 PHP에는 내장 기능과 사용자 정의 기능이라는 두 가지 기능이 있습니다. 이러한 기능에 대해 더 자세히 알아보겠습니다.

예시 #1

문자열 함수의 경우

코드:

<!DOCTYPE html>
<html>
<body>
<?php
print_r(str_split("Hi This is a test sample"));
?>
</body>
</html>

출력:

PHP의 함수

위 프로그램에 대한 설명: 위의 예에서 str_split() 함수 내부에 전달한 문자열은 문자열을 단일 문자로 분할하여 출력을 생성합니다.

예시 #2

코드:

<!DOCTYPE html>
<html>
<body>
<?php
echo strcmp("Hi this is test","Hi this is test");
?>
<p>If this function returns 0, the two strings are same.</p>
</body>
</html>

출력:

PHP의 함수

위 프로그램에 대한 설명: 위 예에서 함수 strcmp()는 문자열을 비교하여 문자열이 동일하면 0을 반환하고 문자열이 동일하지 않으면 0을 반환합니다. 다른 번호를 반환합니다.

예시 #3

코드:

<!DOCTYPE html>
<html>
<body>
<?php
echo strpos("I love coding, I love php too!","coding");
?>
</body>
</html>

출력:

PHP의 함수

The explanation for the above program: This function strpos() will check the position of the string that is passed as a parameter.

Example #4

Code:

<!DOCTYPE html>
<html>
<body>
<?php
echo strrev("Hi world!");
?>
</body>
</html>

Output:

PHP의 함수

The explanation for the above program: In the above example, the function strrev() will reverse the string passed as a parameter and provides the desired output.

Example #5

Code:

<!DOCTYPE html>
<html>
<body>
<?php
echo str_word_count("Hello this is the new world!");
?>
</body>
</html>

Output:

PHP의 함수

The explanation for the above program: In the above example, the str_word_count() function will count the number of strings passed as a parameter and provides the desired output.

Example #6

Code:

<!DOCTYPE html>
<html>
<body>
<?php
echo strlen("Hello this is the test sample!");
?>
</body>
</html>

Output:

PHP의 함수

The explanation for the above program: In the above example, the strlen() function will count the number of characters present in the string and provides the count as the desired output.

Example #1

For Numeric Functions

Code:

<!DOCTYPE html>
<html>
<body>
<?php
echo(abs(5.8) . "<br>");
echo(abs(-5.8) . "<br>");
echo(abs(-2) . "<br>");
echo(abs(3));
?>
</body>
</html>

Output:

PHP의 함수

The explanation for the above program: In the above example, the numeric function abs() will provide us the absolute value of the number that is passed as a parameter to the function.

Example #2

Code:

<!DOCTYPE html>
<html>
<body>
<?php
echo(round(0.65) . "<br>");
echo(round(0.75) . "<br>");
echo(round(0.30) . "<br>");
?>
</body>
</html>

Output:

PHP의 함수

Example #3

Code:

<!DOCTYPE html>
<html>
<body>
<?php
echo(sqrt(0) . "<br>");
echo(sqrt(7) . "<br>");
echo(sqrt(2) . "<br>");
echo(sqrt(0.45) . "<br>");
echo(sqrt(-3));
?>
</body>
</html>

Output:

PHP의 함수

The explanation for the above program: In the above example, the parameters passed to the function sqrt() fetches the result by calculating the square root of the number and produces the desired output.

Example #4

Code:

<!DOCTYPE html>
<html>
<body>
<?php
// Check if the type of a variable is integer or not
$x = 456;
var_dump(is_int($x));
echo "<br>";
// Check whether the type of variable is integer or not
$x = 66.58;
var_dump(is_int($x));
?>
</body>
</html>

Output:

PHP의 함수

The explanation for the above program: In the above example, the var_dump() function will check the data type of a particular number passed as a parameter. In the above screenshot, the output is printed as true or false in the condition that the number should be an integer. If the number is not an integer it will return false else true.

Example #5

Code:

<!DOCTYPE html>
<html>
<body>
<?php
// Invalid calculation will return a NaN value
$x = acos(10);
var_dump($x);
?>
</body>
</html>

Output:

PHP의 함수

The explanation for the above program: In the above example, the function var_dump() will check the datatype of the number passed as a parameter. In this example, the function acos() cannot calculate the number specified as a parameter and hence produces the output NAN which means that the calculation is incorrect.

Example #6

Code:

<!DOCTYPE html>
<html>
<body>
<?php
$x = 11.35;
var_dump(is_float($x));
?>
</body>
</html>

Output:

PHP의 함수

The explanation for the above program: In the above example, the function is_float() will check whether the number passed as a parameter is of float datatype. This function always returns a Boolean value. If the result is positive then it will return true and if the result is negative it will return false.

Example #1

For User-defined functions

Code:

<!DOCTYPE html>
<html>
<body>
<?php
function Writefunction() {
echo "Hello world!";
}
Writefunction();
?>
</body>
</html>

Output:

PHP의 함수

Example #2

Code:

<!DOCTYPE html>
<html>
<body>
<?php
function employee($ename) {
echo "$ename Patil.<br>";
}
employee("Akshay");
employee("Leela");
employee("Sharda");
employee("Subhadra");
employee("Akash");
?>
</body>
</html>

Output:

PHP의 함수

Example #3

Code:

<!DOCTYPE html>
<html>
<body>
<?php
function Employee($ename, $id) {
echo "employee name is $ename. Employee id is $id <br>";
}
Employee("Heetal","778456");
Employee("Clark","567890");
Employee("Mohit","567894");
?>
</body>
</html>

Output:

PHP의 함수

The explanation for the above program: In the above example, the employee names along with the employee id’s can be displayed by just calling the function employee () where the user wants to print the employee details. This user-defined functions can be used when the organization has a huge data and has to print all the employee details all together at a single go.

Example #4

Code:

<?php
function addNumbers(int $a, int $b) {
return $a + $b;
}
echo addNumbers(5, "13 days");
// since strict is NOT enabled "5 days" is changed to int(5), and it will return 10
?>

Output:

PHP의 함수

위 프로그램에 대한 설명: 위의 예에서 우리는 사용자 정의 함수가 고유한 속성을 가지며 사용자가 원하는 출력을 얻기 위해 자신의 입력을 제공할 수도 있음을 확인했습니다. 사용자 정의 함수는 프로그래머나 개발자가 내장 함수를 사용하는 대신 코드를 직접 변경하는 데 사용됩니다. 이 함수 유형을 사용하는 주요 동기는 개발자가 원 면적 계산, 키 측정, 직원 세부 정보 등과 같은 자신만의 논리를 만들 수 있다는 것입니다. PHP는 데이터 유형이 엄격한 방식으로 설정되지 않은 느슨한 유형의 언어를 가지고 있습니다. , 정수 및 문자열 데이터 유형 값을 추가하여 출력을 가져올 수 있습니다. 위의 예에서는 정수와 문자열 "5와 13"을 더하고 출력을 18로 가져옵니다. 이 기능은 사용자에게 유리합니다.

결론

이번 글에서는 PHP의 함수 종류와 특징에 대해 살펴보았습니다. 개발자와 프로그래머는 이 두 가지 기능을 사용하여 코드를 개발하려고 합니다. 코드를 다시 작성할 필요가 없고, 수행해야 하는 작업 유형에 따라 코드가 작성되므로 테스트하기도 쉽습니다.

위 내용은 PHP의 함수의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:PHP call_user_func_array다음 기사:PHP call_user_func_array