Forum Moderators: coopster

Message Too Old, No Replies

PHP5 OOP newbie Q

         

cantona

11:47 am on Oct 16, 2008 (gmt 0)

10+ Year Member



Hi, I am just getting my head round magic functions in PHP 5 (__construct, __distruct, __get and __set)
I'm writing 5 classes and want to use these 4 magic funcs in each one. But duplicating them in each class (about 30 lines) seems inefficient. I was thinking about putting them in a single file and then extending my 5 classes from that.

Would I use a "parent", "interface" or "abstract" structure to do this? and more importantly, will the magic still work from an upper tier!?

Here are my magic funcs that I want to put in an upper tier...


// define attributes
private $data;
private $dbh;

// start by connecting to DB and creating an option object
public function __construct($data = array())
{
foreach($data as $key => $value)
{
$this->$key = $value;
}
$this->dbh = DBConnect(DB_DSN_THESOURCE,true,true);
}

// when finished, disconnect from DB
public function __distruct() {
DBDisconnect($dbh);
}

// get attributes
private function __get($key) {
if(isset($this->data[$key])) {
return $this->data[$key];
}
return false;
}

// set attributes
private function __set($key, $value) {
$this->data[$key] = $value;
}

tumr

7:06 pm on Oct 18, 2008 (gmt 0)

10+ Year Member



Have you considered writing your other classes as:
class ClassName EXTENDS BaseClass{
}

and putting those 4 invariant functions into
class BaseClass{
}

?

If you do this, all 4 functions will have native access to the functions within BaseClass.

cantona

7:36 am on Oct 20, 2008 (gmt 0)

10+ Year Member



Thanks tumr. Yes I was thinking of something like this.
So, to access the funcs in BaseClass() would I have to call them as a parent function? Those 4 would/could also be static right?

"Interface" and "abstract" seem a little complex in comparison. Think I'll leave those alone for now... :)

tumr

8:09 am on Oct 20, 2008 (gmt 0)

10+ Year Member



Yes, exactly. So, say you have constructed ClassName (the baby class) and BaseClass (the parent class). If BaseClass has a function called bigFunction() that echoes out "argument is less than 10", you can access that in ClassName, since it extends BaseClass.

If you wanted to override it in ClassName in certain conditions, here is an example of how you could do that:

bigFunction($argument){
if($argument>=10){
return "$argument is greater than or equal to 10";
}else{
parent::bigFunction();
}
}