我一直在学习一些有关如何创建会话对象的课程,效果很好。如果将完整的代码放在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!";
?>
答案 0 :(得分:1)
我的建议是将此重构过程分为两个步骤:
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();
答案 1 :(得分:1)
您需要在需要使用它的位置“要求”您的文件。
这里有个例子
使用课程:
任何.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
答案 2 :(得分:0)