[英]How to call a function in parent class PHP?
我有两个PHP类。 第一个是这样的:
<?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","");
}
}
?>
我的Login类是:
<?php
class Login{
public function checkDB(){
//**** how do I call mysql on MainClass here ?*****
}
}
?>
我需要提及的是,登录不是Main Class的子类。 所以我想知道如何从Login Class调用MainClass上的mysql
函数吗?
方法1 :派生类
<?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
}
}
?>
方法2 :对象实例
<?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
}
}
?>
注意:不要使用MySQL函数,因为它们已被弃用,因此请使用mysqli
或PDO
连接数据库。
使用此代码,您只需创建MainClass
对象并调用mainClass函数。
<?php
class Login{
public function checkDB(){
$main = new MainClass();
$main->mysql();
}
}
?>
如果您想为此使用面向对象的处理程序,而不是重新发明轮子,请使用mysqli
类。 这里的文档,下面的代码示例:
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
}
正如shapeshifter在评论中所说,您想要一个可以从其他类中引用的类。 相反,我可能会做这样的事情:
<?php
$database = new MainClass();
class Login
{
public function checkDB($database)
{
$database->mysql();
}
}
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.