Reputation: 5
<?
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
Upvotes: 0
Views: 53
Reputation: 4544
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
Upvotes: 0
Reputation: 816
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');
}
}
Upvotes: 1