【发布时间】:2015-07-18 05:24:07
【问题描述】:
假设,我有 2 个文件:
dbconnect.php
calculate.php
calculate 具有抽象类“authx”,其函数为
login、signup、forgotpass、newsDisplay等。为了使函数正常工作,我在类文件中添加了上述函数的实际类“auth”。
DB connect.php 具有所有数据库相关功能,它有类文件
现在,我需要在 Login、Signup、forgotpass.等中使用 DBCON 的对象,一种方法是一次又一次地在每个函数中包含设置,效果很好。
但作为替代和更好的解决方案,我认为在函数内部分配和使用数据库对象会很好,以实现更好的代码流。
dbcon.php
<?php
class dbcon{
function connect(){
$servername = "localhost";
$username = "root";
$password = "";
$dbname="work_steelnext";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
else{
echo "Connected Successfully";
}
}
function disconnect(){
mysqli_close($conn);
}
}
?>
计算.php
<?php
include 'dbCon.php';
/**
* Make the use of JSON a standard thing!
*Do error Handling totally
*Make the Login, Noback, Signup, forgot Password, Deploy it on server,
**/
/**
* Connecting the Database
**/
abstract class auth
{
/**
*Setting the Abstract classes for the Login file
*
**/
abstract function login();
/**
*Developing the Sign Up Module
*
**/
abstract function signup();
/**
*forgot Pass
**/
abstract function forgotpass();
}
/**
*This class will make the login work
**/
/**
*Make a JSON Based Switch
*/
class authx extends auth
{
function jsonhandler(){
//Data Switch for the information
}
function login()
{
}
function signup()
{
// $test = new authx();
// echo $test->forgotpass();
//Wrong way to code is
//$getname="chocolate";
$get_uname=$_GET['signupName'];
$get_uemail=$_GET['signupEmail'];
$get_upwd=$_GET['signupPwd'];
//$get_uemail=$_GET['uemail'];
echo "Variable ".$getname. "<br/>";
//$sql = "INSERT INTO `tb_users`(`u_id`, `u_name`, `u_email`, `u_pwd`) VALUES (null,\"hello\",\"hello\",\"hey\")";
//$sql="INSERT INTO names(name,email) VALUES('$get_uname','$get_uemail')";
$sql="INSERT INTO tb_users(u_id,u_name,u_email,u_pwd) VALUES(null,'$get_uname','$get_uemail','$get_upwd')";
$dblink=new dbCon();
echo $dblink->connect();
$conn="x";
if (mysqli_query($conn, $ sql)) {
echo "New record created successfully";
echo $get_uname."Stored".$get_uemail;
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
function forgotpass()
{
}
function switchandle($a)
{
switch($a)
{
case 'login':
echo "\nlogin entered";
break;
case 'signup':
echo "\nsigningup entered";
break;
case 'forgot':
echo "\nI forgot password";
break;
default :
echo "\nNull";
break;
}
}
}
$test = new authx();
// echo $test->switchandle("login");
echo $test->signup();
?>
【问题讨论】:
-
请包含一些应用程序结构的代码示例,让人们了解您的出发点,以便他们更好地帮助您解决问题。
-
使用自动加载器加载类文件。问题解决了。如果您需要在对象内部使用对象,则将它们作为参数传递(阅读:依赖注入)
标签: php file object scope global