繁体   English   中英

如何在PHP中调用函数

[英]How to call a function in PHP

我一直在学习如何创建会话对象的一些课程,这很好,如果我把完整的代码放到PHP文件上,一切都很棒!

我想做的是将它放在另一个模块(PHP文件)中,只需使用一行(或等效的)来执行此操作,例如GetSessiondata();

<?php
$SqlCon = new DBConnect("Databaselocation","Database","Usr","Pss");                     
$UserDataSet = $SqlCon->GetUserList("SELECT * FROM Users");

echo "<br /><br />";
echo "<br /><br />";

if ($UserDataSet)          
{               
    echo "<table>" . "<thead>" ;
    echo "<tr><th scope=\"col\">" . 'Usr' . "</th>";
    echo "<th scope=\"col\">" . 'Lvl' . "</th></tr></thead><tbody>";                
    foreach($UserDataSet as $data)
    {                                  
        echo "<td>" .$data->GetUsrName()."</td>" ;
        echo "<td>" .$data->GetUsrLevel()."</td></tr>" ;                                       
    }
    echo "<tfoot><tr><th scope=\"row\" colspan=\"2\">" . 'Total Users = 2' . "</th></tr></tfoot>";
    echo "</tbody>" . "</table>" ;  
}
else
    echo "Nothing Found in DB!";
?>

我的建议是将这个重构过程分成两个步骤:

1.将代码包含在函数中:

function someFunctionName() {
    $SqlCon = new DBConnect("Databaselocation","Database","Usr","Pss");                     
    $UserDataSet = $SqlCon->GetUserList("SELECT * FROM Users");

    echo "<br /><br />";
    echo "<br /><br />";

    if ($UserDataSet)          
    {               
        echo "<table>" . "<thead>" ;
        echo "<tr><th scope=\"col\">" . 'Usr' . "</th>";
        echo "<th scope=\"col\">" . 'Lvl' . "</th></tr></thead><tbody>";                
        foreach($UserDataSet as $data)
        {                                  
           echo "<td>" .$data->GetUsrName()."</td>" ;
           echo "<td>" .$data->GetUsrLevel()."</td></tr>" ;                                    
        }
        echo "<tfoot><tr><th scope=\"row\" colspan=\"2\">" . 'Total Users = 2' . "</th></tr></tfoot>";
        echo "</tbody>" . "</table>" ;  
    }
    else
        echo "Nothing Found in DB!";
}

// and call your function
someFunctionName();

2.在同一个目录中创建另一个文件,比如functions.php ,并将函数移入其中。 现在你可以在你的php页面中要求这个文件:

require_once 'functions.php';

// and call your function
someFunctionName();

您需要“需要”您要使用它的文件。

这是一个例子

使用课程:

Whatever.php

class Whatever {
  public function __construct() {
    // Ever when the code is instantiated, this will be called too!
  }
  public function myMethod() {
    echo 'hello';
  }
}

的index.php

require_once('./Whatever.php');
$whatever = new Whatever();
$whatever->myMethod();

没有课程:

的functions.php:

function whatever(){ echo 'hello'; }

index.php文件:

require_once('./functions.php');
whatever();

阅读更多:

要求: http//php.net/manual/es/function.require.php

Require_once: http ://php.net/manual/es/function.require-once.php

我想你正在寻找include

保存文件,然后包含在另一个文件中:

include 'my_file.php';

您还可以使用:

阅读文档以获得进一步说明或查看此问题

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM