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

时间:2011-04-27 04:13:58

标签: php

例如,我有一个文件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;
    }
}

...

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

require_once('error-status.php');

5 个答案:

答案 0 :(得分:25)

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

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

答案 1 :(得分:4)

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

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

答案 2 :(得分:2)

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

答案 3 :(得分:1)

基于Chris所说的,如果你的函数在error-status.php中的一个类中,你需要初始化类并通过它调用函数。

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

答案 4 :(得分:1)

见下面的例子,

first_file.php:

<?php
    function calling_function(){ 
       $string = "Something";
       return $string; 
    }
?>

在你的第二个档案中

second_file.php:

<?php
     include 'first_file.php';
     $return_value = calling_function();
     echo $return_value;
?>
相关问题