Jump to content

Extending Class Accessing Parent Variables


barkster

Recommended Posts

I have a class and I'm trying to extend it to shorten the code when needed.  I'm trying to get the value of a variable in the parent class in the child but I cannot get it?  I've tried setting the var $var1 to public $var1 but still cannot get it.  Here is a simplified version.  How do I get the value of a variable in the child class?  Thanks

 

class db_class {
var $var1
function db($db) {
	$this->var1=$db;
}
}

class paging extends dbclass {

function paging() {

}

function query() {
	$sql = "SELECT * FROM Table";
	//get the parent variable $var1
	$result = mysql_db_query($this->var,$sql);
}
}

 

hymn, I thought I had tried doing that by using the following but maybe it won't work this way.  I'll try it they way you suggest thanks.

 

class db_class {
   var $var1
   function db($db) {
      $this->var1=$db;
   }
}

class paging extends dbclass {
   var $db;
   function paging() {
          $db=parent::var1;
   }

   function query() {
      $sql = "SELECT * FROM Table";
      //get the parent variable $var1
      $result = mysql_db_query($db,$sql);
   }
}

1) Why are you using PHP4 syntax for OOP?  It's horrid.

 

2) It should, in reality, look like:

 

<?php
class DBClass {
    protected $var1;
    public function __construct($var) {
        $this->var1 = $var;
     }
}

class Paging extends DBClass {
  
    public function __construct($var) {
        parent::__construct($var);
    }
    public function getVar() {
        return $this->var1;
    }
}

$p = new Paging('foo');
echo $p->getVar();

 

3) parent::Foo refers to a class constant named Foo in the parent, and parent::$Foo refers to a static variable named $Foo in the parent.

maybe I should stick with it all in one class till I get a grasp on this.  I was just using what I could find on extending a class.  I think I'm going about this in the wrong direction.  I thought that I could call this

 

//create parent object

$db = new db_class;

//set the $db variable in parent

$db->dofunction("db");

//now create the paging object

$pg = new paging;

//now use the $db variable from the parent object in the paging class in function dofunctionchild() mysql_db_query(parent::db,$sql);

$pg->dofunctionchild();

 

I assumed that by extending the class I could easily use variables and functions between the two. I think I should just leave it in one class and do some more reading.  I was just trying to make my class a little smaller and just use the extended class when needed.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.