0
<?

class Flip 
{

    private $db;

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

    public function flips()
    {
        $flips = array();

        $result = $this->db->Select()->Get('flips');
        if($result)
        {
            foreach ($result as $value) 
            {
                $flips[] = $value;
            }
            return $flips;
        }
        return false;
    }

    public function flipComment($id)
    {
        return $this->db->Select()->Where('id', $id)->Get('comments');
    }

}

Fatal error: Using $this when not in object context.

Any ideas how to fix? I don't want to recall class Database for each function. I need to be able to use $this->db

3
  • Can you post a full class declaration? $this is used inside the class declaration. Otherwise you need to use a instance name. Commented Jul 9, 2015 at 3:01
  • Can you please show the full error message , which line does this error occurs ? Commented Jul 9, 2015 at 3:31
  • The code you have pasted thus far is valid. You need to show the full error message including line number, and make sure you are copy/pasting exactly your code. Commented Jul 9, 2015 at 3:43

2 Answers 2

1

You cannot use $this because the functions are not part of a class.

    Class MyClass {
        private $db;

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

        public function comment()
        {
            $this->__construct();

            return $this->db->Select()->Get('comments');
        }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Make your variable static and in the constructor you can see if it's already set. Then you will only have to open the connection once and every time you call Flip it will be able to use that connection.

class Flip
{
    private static $db;

    function __construct()
    {
        if (!isset(self::$db))
            self::$db = new Database();
    }

    function comment()
    {
        return self::$db->Select()->Get('comments');
    }
}

More on the static keyword

5 Comments

I don't wanna recall the class Database.
what do you mean by recall? do you mean you don't want to make a new connection to the database?
I wrote an interpreter database class that is crafts my query and I would like to save memory by only needing to call it once inserted of each function requiring the class
Call to a member function Select() on a non-object
Did you fix my typo $b-> should be $db->. I will edit that in my answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.