Results 1 to 2 of 2

Thread: Fatal error: Call to a member function query() on a non-object in D:\wokspace\rts_sea

  1. #1
    Join Date
    Jun 2011
    Posts
    12
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Fatal error: Call to a member function query() on a non-object in D:\wokspace\rts_sea

    <?php
    class DB{

    private $link;

    public static function connect($host,$user,$passwd,$dbname) {
    $db=new DB();
    $db->link = new mysqli($host,$user,$passwd,$dbname);
    return $db;
    }
    public function query($sql) {
    return $this->link->query($sql);
    }

    }
    ?>
    iam getting such error for above code

  2. #2
    Join Date
    Mar 2007
    Location
    New York, NY
    Posts
    557
    Thanks
    8
    Thanked 66 Times in 66 Posts

    Default

    You can't create an instance of the same class within itself that you are defining. In this case, you're referencing the class DB within the function connect() which is inside the DB class.

    Why don't you try creating the instance after the class and defining the variables as constructors?

    PHP Code:
    <?php
    class DB{

    private 
    $link;

    public static function 
    connect($host,$user,$passwd,$dbname) {
    $this->link = new mysqli($host,$user,$passwd,$dbname);
    return 
    $this->link;
    }

    public function 
    query($sql) {
    return 
    $this->link->query($sql);
    }

    }

    $db = new DB();
    $db->connect("""""""");

    ?>

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •