php 我将如何调用另一个文件中的函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5799267/
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 would I call a function in another file?
提问by Harsh
For example, I have a file error-status.php, which includes a function:
例如,我有一个文件 error-status.php,其中包含一个函数:
function validateHostName($hostName)
{
if ((strpbrk($hostName,'`~!@#$^&*()=+.[ ]{}\|;:\'",<>/?')==FALSE) && !ctype_digit($hostName) && eregi("^([a-z0-9-]+)$",$hostName) && ereg("^[^-]",$hostName) && ereg("[^-]$",$hostName))
{
return true;
}
else
{
return false;
}
}
...
...
How do I call that function from a different PHP file after invoking require_once
?
调用后如何从不同的 PHP 文件调用该函数require_once
?
require_once('error-status.php');
回答by Chris
Include the file before you call the function.
在调用函数之前包含文件。
include 'error-status.php';
validateHostName('myhostname');
回答by Portu
I would simply extend the class or use the require /include
, then:
我会简单地扩展类或使用 require /include
,然后:
$var = new otherClass;
$getString = $var->getString();
回答by dm7
include or require the file before you call the function.
在调用函数之前包含或需要该文件。
回答by Camro
Building on what Chrissaid, if your function is inside a class in error-status.php, you'll need to initialise the class and call the function through that.
根据Chris所说,如果您的函数位于 error-status.php 中的一个类中,您将需要初始化该类并通过它调用该函数。
回答by A.A Noman
See an example below,
看下面的例子,
first_file.php :
first_file.php :
<?php
function calling_function(){
$string = "Something";
return $string;
}
?>
In your Second file
在你的第二个文件中
second_file.php :
second_file.php :
<?php
include 'first_file.php';
$return_value = calling_function();
echo $return_value;
?>