I have two PHP classes. The first one is like :
<?php
$myclass = new MainClass;
class MainClass{
public $login;
public function __construct(){
require_once('login.class.php');
$this->login = new login;
}
public function mysql(){
mysql_connect("localhost","root","");
}
}
?>
And my Login class is :
<?php
class Login{
public function checkDB(){
//**** how do I call mysql on MainClass here ?*****
}
}
?>
I need to mention that Login is Not child class of Main Class. So I'm wondering how to call mysql
function on MainClass from Login Class ?
Method1: : Derived class,
<?php
require_once('MainClass.php'); // MainClass store as a php file
class Login extends MainClass{
public function checkDB(){
$this->mysql(); //**** call mysql from MainClass here
}
}
?>
Method2: : Object instance,
<?php
require_once('MainClass.php'); // MainClass store as a php file
$check_mysql = new MainClass();
class Login extends MainClass{
public function checkDB(){
$check_mysql->mysql(); //**** call mysql from MainClass here
}
}
?>
Note: Don't use MySQL functions because they are deprecated, so use mysqli
or PDO
for connecting DB.
use this code, you just have to create object of MainClass
and call the mainClass function.
<?php
class Login{
public function checkDB(){
$main = new MainClass();
$main->mysql();
}
}
?>
If you want to use an object-oriented handler for this, instead of reinventing the wheel, use the mysqli
class. Documentation here , code example below:
class Login extends mysqli {
public function __construct($loginid) {
$this->id = $loginid; // example of wrapping
parent::__construct( /* login constants go here */ );
}
. . .
// other functions that can have direct access to the mysqli:: class
}
As shapeshifter said in the comments, you want a class that you can reference from other classes. Instead, I would probably do something like this:
<?php
$database = new MainClass();
class Login
{
public function checkDB($database)
{
$database->mysql();
}
}
?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.