How to call function of one php file from another php file and pass parameters to it?

前端 未结 4 933
滥情空心
滥情空心 2020-12-07 19:46

I want to call a function in one PHP file from a second PHP file and also pass two parameters to that function. How can I do this?

I am very new to PHP. So please te

相关标签:
4条回答
  • 2020-12-07 20:01

    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.

    0 讨论(0)
  • 2020-12-07 20:03

    Yes include the first file into the second. That's all.

    See an example below,

    File1.php :

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

    Now Using include (http://php.net/include) to include the File1.php to make its content available for use in the second file:

    File2.php :

    <?php
      include 'File1.php';
      echo first(1,"omg lol"); //returns omg lol;
    ?>
    
    0 讨论(0)
  • 2020-12-07 20:20

    files directory:

    Project->

    -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);
    

    The Output Is :

    sum of two numbers 6 product of two numbers 6

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

    0 讨论(0)
  • 2020-12-07 20:21

    file1.php

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

    file2.php

    <?php
    
        require_once('file1.php');
    
        func1('Hello', 'world');
    

    See manual

    0 讨论(0)
提交回复
热议问题