如何在php中将类的对象用于另一个类

时间:2018-03-02 18:18:11

标签: php oop

<?php 

class connect {
public $_link,$_result,$_num_rows;

public function __construct() {
    $this->_link = new mysqli("localhost","root","","news");
}

public function query($sql) {

    $_result = $this->_link->query($sql);
    return $this->_result;
}
public function num_rows($result) {
    $this->_num_rows = $result->num_rows;
    return $this->_num_rows;
}
}
<?php 
require "../model/connect.php";
$db = new connect();
$mydoLogin = new doLogin($db);

class doLogin  {
protected $mycon ;
public function __construct($mycon) {
    $this->mycon = $mycon;
}
public function is_user_exist($user,$pass) {
    $sql = "select * from user where username=$user and password=$pass";
    $result = $this->mycon->_link->query($sql);
    return ($this->mycon->num_rows($result) == 1);
    //var_dump($result);
 }



}

我有类,首先是连接类,然后是doLogin类,所以我想将连接类的实例用于doLogin类,但是当我想使用它时,我面临很多错误,有时它会说mycon变量没有被定义或者......在这里,我试图多次直接在doLogin类中创建实例,但我不能。帮助我解决这个问题。谢谢!

2 个答案:

答案 0 :(得分:0)

<p>Here i have two classes,
1)Main.php ->create one contrsuct() function do the connection inside the function for example </p>
<pre>

class Main {
    protected $conn = null;
public function __construct(){

try{
    $this->conn = new PDO(DB_TYPE.":host=".DB_SERVER.";dbname=".DB_DATABASE, DB_USER, DB_PASSWORD);
    $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e){

echo '<h3>Database Not Connected</h3>','<p>Please Check database connection before running this site ...</p>'; 
exit;

}

}
}

</pre>
<p>inside the same class only create another function for login for example</p>
<pre>
 public function isLogged($sessionId, $url){
    if(isset($_SESSION[$sessionId])){
        $this->redirect($url);
    }
}
</pre>

now create another class it extends main class and doing the login calculation
for example:-

    <pre>


  Class Login extends Main{
       public function loginCollege($username,$password)
    {
        try{
            $stmnt=$this->conn->prepare("select id from colleges where(email=:user or phone=:user)  AND phone=:pswd");
            $stmnt->bindParam("user", $username,PDO::PARAM_STR) ;
            $stmnt->bindParam("pswd", $password,PDO::PARAM_STR) ;
            $stmnt->execute();
            $count=$stmnt->rowCount();
            $res=$stmnt->fetch(PDO::FETCH_ASSOC);
            $id = $res['id'];
            if($count){
                $_SESSION['id']= $id;
                return true;
            }else{
                return false;
            }

        }catch(PDOException $e) {
                echo '{"error":{"text":'. $e->getMessage() .'}}';
        }

    }
   }

</pre>

答案 1 :(得分:0)

无需连接数据库,尝试使用一类连接,并使用另一个文件,不创建类,并在第二个文件中创建该类的实例。