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