php 如何从另一个php文件调用一个php文件的函数并将参数传递给它?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8104998/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to call function of one php file from another php file and pass parameters to it?
提问by Pushpendra Kuntal
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?
我想从第二个 PHP 文件中调用一个 PHP 文件中的函数,并将两个参数传递给该函数。我怎样才能做到这一点?
I am very new to PHP. So please tell me, should I include the first PHP file into the second?
我对 PHP 很陌生。所以请告诉我,我应该将第一个 PHP 文件包含在第二个中吗?
Please show me an example. You can provide some links if you want.
请给我举个例子。如果需要,您可以提供一些链接。
回答by Mob
Yes include the first file into the second. That's all.
是的,将第一个文件包含在第二个文件中。就这样。
See an example below,
看下面的例子,
File1.php :
文件 1.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 includethe File1.php
to make its content available for use in the second file:
现在,使用include
(http://php.net/include)到包括在File1.php
作出其内容可在第二个文件使用:
File2.php :
文件 2.php :
<?php
include 'File1.php';
echo first(1,"omg lol"); //returns omg lol;
?>
回答by Dmitry Teplyakov
回答by Hafiz Shehbaz Ali
files directory:
文件目录:
Project->
项目->
-functions.php
-functions.php
-main.php
-main.php
functions.php
函数.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
两个数的和 6 两个数的乘积 6
Note: don't write public before function. Public, private, these modifiers can only use when you create class.
注意:不要在函数之前写public。public、private,这些修饰符只能在创建类时使用。
回答by Abubkr Butt
you can write the function in a separate file (say common-functions.php) and include it wherever needed.
你可以在一个单独的文件中编写函数(比如 common-functions.php),并在需要的地方包含它。
function getEmployeeFullName($employeeId) {
// Write code to return full name based on $employeeId
}
You can include common-functions.php in another file as below.
您可以将 common-functions.php 包含在另一个文件中,如下所示。
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.
您可以将任意数量的文件包含到另一个文件中。但是包含会带来一些性能成本。因此只包含真正需要的文件。