我有一个类文件,在类文件中有一些代码。如何跨多个页面共享代码。这段代码处理了在使用预处理语句
时获取结果集的问题。代码如下。我如何重用函数mps_fetch_assoc。我希望代码只在一个地方。
<?php
//http://localhost:8080/altenaontw/index.php?-action=showclient
class actions_showclient
{
// find here http://www.meetup.com/austinphp/messages/boards/thread/2022681
private function mps_fetch_assoc(&$stmt)
{
$meta = $stmt->result_metadata();
$retval[] = &$stmt;
$tmp;
$names;
while ($field = $meta->fetch_field())
{
$names[] = $field->name;
}
$tmp = $names;
for ($c = 0; $c < count($names); $c++)
{
$retval[] = &$tmp[$c];
}
call_user_func_array("mysqli_stmt_bind_result", $retval);
if ($stmt->fetch())
{
$assoc_array;
for ($c = 0; $c < count($names); $c++)
{
$assoc_array[$names[$c]] = $retval[$c + 1];
}
return $assoc_array;
}
else
{
return FALSE;
}
}
function handle($params)
{
header('Content-type: text/json; charset="UTF-8"');
$user = Dataface_AuthenticationTool::getInstance()->getLoggedInUser();
if (!$user)
{
return Dataface_Error::permissionDenied("U heeft geen toegang tot deze actie.");
}
$db = Dataface_Application::getInstance()->_conf['_database'];
echo ($db['host']);
//$mysqli = new mysqli($db['host'], $db['user'], "", $db['name']);
$mysqli = mysqli_connect($db['host'], $db['user'], "", $db['name']);
/* check connection */
if ($mysqli->connect_errno)
{
printf("Connect failed: %s'n", $mysqli->connect_error);
exit();
}
$sql = 'SELECT * from client';
$stmt = $mysqli->prepare($sql);
if ($stmt)
{
$result = $stmt->execute();
if (!$result)
{
echo "[" . json_encode(array('dberror' => 'db_error:' . mysql_error())) . "]";
return;
}
$rows = array();
while ($row = $this->mps_fetch_assoc($stmt))
{
$rows[] = $row;
}
print json_encode($rows);
$mysqli->close();
}
}
}
?>
你必须使用include()。在这里看到的:phpnet包括()
您应该使用<?php include 'name_of_file.php'; ?>
您应该在任何想要使用类的页面中包含您的类文件。你可以这样做:
<?php include 'file_to_include.php'; ?>
之后,当你计划调用函数而不创建新对象时,你应该这样做:
<?php actions_showclient::mps_fetch_assoc($variable); ?>
如果你将添加一个"__construct"函数到你的类,你可以调用函数以不同的方式,但我建议你尝试采取一些教训www.codeacademy.com。他们会教你使用类的基本知识。
另外,请确保您希望您的函数是私有的,因为这对您何时能够调用它有一定的影响(查看此信息:公共,私有和受保护之间的区别是什么?)。
祝你好运!
另一种好方法是类自动加载,节省了在单个文件中使用许多include()来让所有内容都工作的时间。
查看此处了解更多:http://php.net/manual/en/language.oop5.autoload.php