developer tip

다른 PHP 파일에서 한 PHP 파일의 함수를 호출하고 매개 변수를 전달하는 방법은 무엇입니까?

optionbox 2020. 7. 25. 10:50
반응형

다른 PHP 파일에서 한 PHP 파일의 함수를 호출하고 매개 변수를 전달하는 방법은 무엇입니까?


두 번째 PHP 파일에서 하나의 PHP 파일로 함수를 호출하고 해당 함수에 두 개의 매개 변수를 전달하고 싶습니다. 어떻게해야합니까?

저는 PHP를 처음 접했습니다. 첫 번째 PHP 파일을 두 번째 PHP 파일에 포함시켜야합니까?

예를 보여주세요. 원하는 경우 일부 링크를 제공 할 수 있습니다.


예, 첫 번째 파일을 두 번째 파일에 포함하십시오. 그게 다야.

아래 예를 참조하십시오.

File1.php :

<?php
  function first($int, $string){ //function parameters, two variables.
    return $string;  //returns the second argument passed into the function
  }
?>

지금 사용 include( http://php.net/include )하는 (가) File1.php두 번째 파일에 사용하기 위해 컨텐츠를 사용할 수 있도록 :

File2.php :

<?php
  include 'File1.php';
  echo first(1,"omg lol"); //returns omg lol;
?>

file1.php

<?php

    function func1($param1, $param2)
    {
        echo $param1 . ', ' . $param2;
    }

file2.php

<?php

    require_once('file1.php');

    func1('Hello', 'world');

매뉴얼 참조


파일 디렉토리 :

프로젝트->

-functions.php

-main.php

functions.php

function sum(a,b){
 return a+b;
}
function product(a,b){
return a*b;
}

main.php

require_once "functions.php";
echo "sum of two numbers ". sum(4,2);
echo "<br>"; //  create break line
echo "product of two numbers ".product(2,3);

출력은 :

두 숫자의 합 6 두 숫자의 곱 6

Note: don't write public before function. Public, private, these modifiers can only use when you create class.


you can write the function in a separate file (say common-functions.php) and include it wherever needed.

function getEmployeeFullName($employeeId) {
// Write code to return full name based on $employeeId
}

You can include common-functions.php in another file as below.

include('common-functions.php');
echo 'Name of first employee is ' . getEmployeeFullName(1);

You can include any number of files to another file. But including comes with a little performance cost. Therefore include only the files which are really required.

참고URL : https://stackoverflow.com/questions/8104998/how-to-call-function-of-one-php-file-from-another-php-file-and-pass-parameters-t

반응형