Web Hosting Talk







View Full Version : Using PHP Classes Within a Class


smidwap
12-08-2002, 01:01 AM
I am writing a php script in which it would be very convenient to be able to call a class within another class.

The working class would look something like:
Class Template
{
$db = new DB;
function something ()
{
$db->mysql_something($someparams);
}
}

However, I have not found a way to use any functions or variables within the $db class. When running this php script (with of course all other required syntax), I get some php errors. I'm just curious if anyone knows a way to do this.

MarkIL
12-08-2002, 03:15 AM
First off, you dont initialize class members outside any member functions. Second, refer to data members with $this.

For example:


class A {
var $a;
function A($a='') { $this->a = $a; }
}

class B {
var $a_inst;
function B($b=''){
$this->a_inst = new A($b);
print $this->a_inst->a;
}
}

$b = new B('Hello, PHP'); // should print "Hello, PHP"

smidwap
12-08-2002, 11:02 AM
Thanks.

I did understant about referring to data members as $this, but I guess I wasn't using the correct syntax to use outside class members. Makes perfect sense now. Thanks again.