从包含的文件中调用函数?

时间:2011-05-03 11:52:04

标签: php function include

我正在编写一个PHP脚本,为我做一些事情,所以我不必在我的网站文档中反复输入所有代码。

以下是我的工作:

// MyFunc.php
<?php
 function DoStuff()
 {
  $var = 'something'; 
  return $var;
 }
?>


// index.php
<html>
<head></head>
<body>
 Hi, I am currently doing <?php include "MyFunc.php"; echo DoStuff(); ?>, pretty cool, right?
</body>
</html>

然而,似乎我的功能没有被调用。我做错了吗?

以下是我的完整资料

//splashgen.php
<?php

$refid = $_GET['ref'];
$output = 'Company';

function GetSponsor()
{

    if($refid!='')
    {
        $dbhost = "localhost";
        $dbuser = "myuser";
        $dbpass = "mypass";

        $dbname = "mydb";

        $sqlselect = "SELECT * FROM egbusiness_members WHERE loginid='$refid';";

        $con = mysql_connect($dbhost,$dbuser,$dbpass) or die('Unable to connect to Database Server!');
        mysql_select_db($dbname) or die('Could Not Select Database!');

        $refid   = stripslashes($refid);
        $refid   = mysql_real_escape_string($refid);

        $result = mysql_query($sqlselect);

        while ($row = mysql_fetch_array($result))
           {
            $output = $row['name_f']." ".$row['name_l']." (".$refid.")";  
           } 
        mysql_close($con); 
    }   
    return $output;

}


?>

/////////

// index.php

...

<font style="font-size:19px" color="#0093C4" face="Calibri"><b>
This page was brought to you by: <?php $_GET['ref']; include "../splashgen.php"; echo GetSponsor(); ?> 
</b></font></div>
...

6 个答案:

答案 0 :(得分:3)

<body>
 Hi, I am currently doing <?php include "MyFunc.php";  echo DoStuff(); ?>, pretty cool, right?
</body>

并确保您的php文件应以<?php

开头

答案 1 :(得分:2)

您希望DoStuff()(带括号)实际调用该函数。除此之外,您的代码还可以。

答案 2 :(得分:1)

缺少括号?

echo DoStuff();

答案 3 :(得分:1)

你忘了在函数调用中添加括号..更改

    <body>
     Hi, I am currently doing <?php include "MyFunc.php"; echo DoStuff; ?>, 
pretty cool, right?
    </body>

    <body>
     Hi, I am currently doing <?php include "MyFunc.php"; 
echo DoStuff(); ?>, pretty cool, right?
    </body>

<强>更新

在您的“完整来源”中回复您的更新..

更改

function GetSponsor() {

function GetSponsor($refid) {

和HTML

更改

<font style="font-size:19px" color="#0093C4" face="Calibri"><b>
This page was brought to you by: <?php $_GET['ref']; 
include "../splashgen.php"; echo GetSponsor(); ?> 
    </b></font>

类似

<font style="font-size:19px" color="#0093C4" face="Calibri"><b>
This page was brought to you by: 
<?php 
include "../splashgen.php"; 
$refid = $_GET['ref']; 
echo GetSponsor($refid); ?> 
</b></font>

我还建议你清理这个$ refid,这样你就不会进行sql注射......

答案 4 :(得分:1)

我认为这是因为我使用的是一个未在函数中声明的变量,显然函数需要一个参数,如下所示:

Function DoStuff($var)
{
  if($var != '')
  {
   return 'I am currently '.$var;
  }
}

...

echo DoStuff('posting on Stack Overflow');

答案 5 :(得分:0)

你检查了包含的位置是否合适?尝试添加“echo”hello world“;在MyFunc.php中的函数之外,只是为了确保它被调用。