166

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 tell me, should I include the first PHP file into the second?

Please show me an example. You can provide some links if you want.

Don't Panic
  • 41,125
  • 10
  • 61
  • 80
Pushpendra Kuntal
  • 6,118
  • 20
  • 69
  • 119

4 Answers4

214

Yes require 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 require (http://php.net/require) to require the File1.php to make its content available for use in the second file:

File2.php :

<?php
require __DIR__ . '/File1.php';
echo first(1, "omg lol"); //returns omg lol;
hakre
  • 193,403
  • 52
  • 435
  • 836
Mob
  • 10,958
  • 6
  • 41
  • 58
  • 12
    To prevent unauthorized access to the file content with all your functions in it, bury the functions (File1.php) above the DOCUMENT_ROOT and change its permissions to 'rwxr-x--x'. – Kirk Powell Apr 11 '16 at 18:46
  • Unauthorized access to the file content should not be a problem since PHP is a server-side language, and so its contents will never get the the browser. See https://stackoverflow.com/questions/4299571/can-php-files-be-viewed-across-the-internet-like-html-files – Dennis H Aug 11 '22 at 20:03
50

file1.php

<?php

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

file2.php

<?php

    require_once('file1.php');

    func1('Hello', 'world');

See manual

Dmitry Teplyakov
  • 2,898
  • 5
  • 26
  • 46
11

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.

Matthew
  • 472
  • 2
  • 5
  • 12
Hafiz Shehbaz Ali
  • 2,566
  • 25
  • 21
10

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.

Abubkr Butt
  • 101
  • 1
  • 3