我如何在另一个文件中调用函数?

时间:2022-04-01 16:00:41

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?

如何在调用require_once后从其他PHP文件中调用该函数?

require_once('error-status.php');

5 个解决方案

#1


24  

Include the file before you call the function.

在调用函数之前包括该文件。

include 'error-status.php';
validateHostName('myhostname'); 

#2


4  

I would simply extend the class or use the require /include, then:

我只是扩展类或使用require / include,然后:

$var = new otherClass;
$getString = $var->getString();

#3


2  

include or require the file before you call the function.

在调用函数之前包含或要求文件。

#4


1  

Building on what Chris said, 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中的一个类中,你需要初始化类并通过它调用函数。

http://php.net/manual/en/keyword.class.php

http://php.net/manual/en/keyword.class.php

#5


1  

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

#1


24  

Include the file before you call the function.

在调用函数之前包括该文件。

include 'error-status.php';
validateHostName('myhostname'); 

#2


4  

I would simply extend the class or use the require /include, then:

我只是扩展类或使用require / include,然后:

$var = new otherClass;
$getString = $var->getString();

#3


2  

include or require the file before you call the function.

在调用函数之前包含或要求文件。

#4


1  

Building on what Chris said, 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中的一个类中,你需要初始化类并通过它调用函数。

http://php.net/manual/en/keyword.class.php

http://php.net/manual/en/keyword.class.php

#5


1  

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