...

View Full Version : Quick Class Question



binaryWeapon
07-28-2008, 02:57 AM
Hopefully it's quick. Here's my code:


class dbproject {
var $dbsys;

function dbproject($dbsys) {
$this->$dbsys=$dbsys;
}

}

$dbp=new dbproject('mysql');
echo $dbp->dbsys;

How would I echo the $dbsys var, which is an object in the dbproject class. I'm familiar with it in javascript, it would be dbp.dbsys, but the last line (echo $dbp->dbsys;) doesn't work. Am I constructing the class wrong? I've just got into PHP OOP, so this stuff is rather new.

Fou-Lu
07-28-2008, 03:30 AM
Yes, the constructor is incorrect:


function dbproject($dbsys) {
$this->$dbsys=$dbsys;
}
// Should be
function dbproject($dbsys)
{
$this->dbsys = $dbsys;
}

Its the $this->$dbsys thats incorrect, you just need $this->dbsys. If you have it available, I'd recommend using PHP5 style OOP, which more accurately reflects an OO style programming language:


class dbproject
{
private $dbsys;

public function __construct($dbsys)
{
$this->dbsys = $dbsys;
}
public function getDBSys()
{
return $this->dbsys;
}

}

$dbp = new dbproject('mysql');
echo $dbp->getDBSys();

The scopes give you far greater control over the properties, what can and cannot be retrieved, and how values are set. PHP5 style also lets you create object patterns, in this case a singleton factory pattern would work quite well which would force only the creation of one dbproject at a time. Patterns are quite a complex methodology since its so abstract, but a quick search on the web for a PHP singleton would give you an idea what its about!

Hope that helps!

binaryWeapon
07-28-2008, 03:35 AM
Thanks for the help! As for php5, I'm interested in making this app that I'm developing compatible with php4.x, but I'll be using php5 on my personal site.

Fou-Lu
07-28-2008, 03:37 AM
No problem, I understand the backwards compatibility. I'm waiting until 6 is released before I finally retire my PHP4 code, just like I waited until 5 to retire my PHP3 code :P



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum