Using $this->var or self::var
Moderator: General Moderators
Using $this->var or self::var
Is there any difference between using $this->var or self::var? Do you have an preference between the two? Any reason why?
$this->var refers to the var property of the current object where as self::var refers to the (usually static) property of the class
Examples:
Also if you overload your methods, using parent:: or self:: to use the child or parent method respectively.
Examples:
Code: Select all
class A
{
private foo;
private static bar = 5;
public function __construct ($var)
{
$this->foo = $var;
}
public static useBar ()
{
return self::bar;
}
}
Last edited by Jenk on Mon Aug 14, 2006 4:13 am, edited 1 time in total.
Ok, am I using it out of context in this class then?
Code: Select all
<?php
class dbcon {
private static $instance = false;
private $linkid = null;
private function __construct() {
if (!self::linkid = @mysql_connect(MYSQL_DATABASE_HOST, MYSQL_USERNAME, MYSQL_PASSWORD))
{
new fatal_exception("FATAL: Database connection failure: " . mysql_errno() . ': ' . mysql_error());
}
}
public static function get_db_link()
{
if ($instance === false)
{
self::$instance = new dbcon;
}
return self::linkid;
}
public function select_db($db = MYSQL_DATABASE_NAME) {
if (!@mysql_select_db($db, self::linkid))
{
new fatal_exception("FATAL: Database selection failure: " . mysql_errno() . ': ' . mysql_error());
}
}
}
?>yes and no. Your property linkid can be static, and is treated as static by your object. However if you were to change it to $this->linkid, you would need to adjust your class definition and the static method get_db_link() to some thing like (note the addition of method getLink()):
Or you can stick the keyword static infront of the property declaration for semantics sake, and leave as is. 
Code: Select all
class dbcon {
private static $instance = false;
private $linkid = null;
private function __construct() {
if (!$this->linkid = @mysql_connect(MYSQL_DATABASE_HOST, MYSQL_USERNAME, MYSQL_PASSWORD))
{
new fatal_exception("FATAL: Database connection failure: " . mysql_errno() . ': ' . mysql_error());
}
}
public static function get_db_link()
{
if ($instance === false)
{
self::$instance = new dbcon;
}
return self::$instance->getLink();
}
public function getLink ()
{
return $this->linkid;
}
public function select_db($db = MYSQL_DATABASE_NAME) {
if (!@mysql_select_db($db, $this->linkid))
{
new fatal_exception("FATAL: Database selection failure: " . mysql_errno() . ': ' . mysql_error());
}
}
}- Christopher
- Site Administrator
- Posts: 13596
- Joined: Wed Aug 25, 2004 7:54 pm
- Location: New York, NY, US