Reputation: 105
I basically have 3 important files right now. I want to use a function from the DB class in the LOGIN class. These are my files. I tried including the DB class but then I would be declaring it twice, which you cant do.
---- index.php ---- -- Which displays the content --
<?php
session_start();
include './libs/database.php';
$mysql = new Database();
include './libs/login.php';
$login = new Login();
$mysql->connect("---", "user", "pass");
$mysql->usedatabase("db");
?>
<!DOCTYPE html>
<html>
<body>
<div id="wrapper">
CONTENT GOES HERE
</div>
</body>
</html>
---
---login.php ---
class Login{
public function isLoggedIn(){
if(isset($_SESSION['user_id'])){
return true;
}else{
return false;
}
}
public function UserLogin($email,$password){
// login function
$DB->selectwhere(...);
}
public function securePassword($pass){
$pass = md5($pass);
return $pass;
}
}
---
--- database.php ---
class Database{
//Database Functions
}
Upvotes: 0
Views: 543
Reputation: 1063
Make the securePassword() function in Login a static function so you can call it without an instance of the Login class.
Login::securePassword()
Upvotes: 1
Reputation: 1933
Read the PHP.net documentation about the keyword extends: http://www.php.net/manual/en/language.oop5.basic.php#language.oop5.basic.extends
A class can inherit the methods and properties of another class by using the keyword >extends in the class declaration.
So your login class will be
class Login extends Database{
public function isLoggedIn(){
if(isset($_SESSION['user_id'])) {
return true;
}
else {
return false;
}
}
public function UserLogin($email,$password){
parent::login();
}
public function securePassword($pass){
$pass = md5($pass);
return $pass;
}
}
You can access a property or method of the Database class using
parent::var_name
parent::method()
Upvotes: 0
Reputation: 1097
Move your Database class to file Database.php. At the top of index.php, use require_once('Database.php'); to include the Database class. Then change UserLogin() function to this:
public function UserLogin($email,$password){
// login function
$DB = new Database;
$DB->selectwhere(...);
}
Upvotes: 0
Reputation: 45
Look into PHP's "Autoload" capabilities. You can actually look up classes on-demand ONLY when they don't already exist in the heap.
Upvotes: 2