douji0073 2013-05-14 15:21
浏览 76
已采纳

函数依赖PHP

So in php im trying to get a public variable in the database class that connects to a database when the class is created. Like so -

<?php

class database {    

    public $_link;


    public function __construct (){
       $this->_link = new PDO("mysql:host=localhost; dbname=swinkidc_student", "swinkidc_student", "");
    }


}

and...

<?php

class user{

    private $db;


    public function __construct() {
        $this->db = new database;
    }

    /**
     * Returns the ID of a user.
     * @param string $user
     * @return mixed
     */
    public function getUserID($user){
        $query =  $_link->prepare("SELECT `user_id` FROM `users` WHERE `username` = :user");
        $query->bindParam(":user", $user);
        $query->execute();       
        $result = $query->fetch(PDO::FETCH_ASSOC);
        return $result['user_id']; 
    }

    /**
     * Checks if given user is active.
     * @param string $user
     * @return bool Returns true/false if user is active.
     */
    public function isUserActive($user){

    }

}

If I extened database in user I can obviously refer to _link if i make it private and it will work, however, I don't think that i should inherit just for getting something like that..

Whenever i try the about i get : Fatal error: Call to a member function prepare() on a non-object in /home/swinkidc/public_html/studentreach/core/authentication/user.php on line 18

As said, if i try the inheritance way it will work, I just don't feel like thats a great way of doing something like this.

Any suggestions please?

Thanks!

  • 写回答

4条回答 默认 最新

  • duanhaodi4809 2013-05-14 15:25
    关注

    link is actually a property of database and not a property of user. Therefore use:

    $query =  $this->db->_link->...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改