PHP - Extending A Class - Why Can't I Access A Parent Method In A Child
I have these two classes:
Code: [Select] <?php class A { private $id; public function __construct() { $this->id = '11111'; } public function getProperty($prop) { return $this->$prop; } }?> Code: [Select] <?php class B extends A { private $message = "Nope, can't see it"; public function __construct() { parent::__construct(); $this->message = "Yep, I can see it"; } }?> I tried this, but it just outputs the id (the first call) Code: [Select] $class = new B; echo $class->getProperty('id'); echo $class->getProperty('message'); Why is that? I thought I could use a parent method on a child property.. *EDIT* Using a public or protected visibility on the message property gets me the output I expect...how come? Similar TutorialsHi, I've a two classes A,B. A is a parent class and B is a child class. B is extends from A. I made an object of class A. Now i want to access function of class B from this object instance. e.g Code: [Select] class A { function myfunctiona() { ....... ....... } } class B extends A { function chlidfunction() { return "hyne"; } } $sani = new A(); //here i want to access echo $sani->b->childfunction(); please guide how can called child class function from parent object instance? Thanks I have a user class that is very dependent on the database class, which is why the user class extends the database. I tried creating a protected method in the parent class called getDBCObject, which returned the database object/variable/handle that I want the user to have access to. I tried the method below, but it doesn't work: <?php /* * @DATABASE * ~~~~~~~~~~~~ * @FILE DESCRIPTION: Handles all database related processes * @LAST MODIFIED: April 4, 2012 */ class database { protected $dbc; function __construct($db_host, $db_name, $db_user, $db_password) { try { $this->dbc = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_password); } catch(PDOException $e) { echo '<b>An error occured while trying to create a database connection: </b>'. $e->getMessage(); } } /* * @METHOD getDBCObject * @DESC Gives the $dbc object/variable to its child classes */ protected function getDBCObject() { return $this->dbc; } } ?> My user class: <?php /* * @DATABASE * ~~~~~~~~~~~~ * @FILE DESCRIPTION: User related proccess * @LAST MODIFIED: April 5, 2012 */ class user extends database { protected $dbc; public function __construct() { if(parent::getDBCObject() == null) { echo '<br/>A database class/connection is required before creating the user class.'; } } public function isLoggedIn() { if($_COOKIE['user']) { //soon to come } else { return false; } } } ?> Any feedback on how I can let the user class use the $dbc variable in the database class? I have mysqli object in Database class base: [color=]database class:[/color] class Database { private $dbLink = null; public function __construct() { if (is_null($this->dbLink)) { // load db information to connect $init_array = parse_ini_file("../init.ini.inc", true); $this->dbLink = new mysqli($init_array['database']['host'], $init_array['database']['usr'], $init_array['database']['pwd'], $init_array['database']['db']); if (mysqli_connect_errno()) { $this->dbLink = null; } } } public function __destruct() { $this->dbLink->close(); } } Class derived is Articles where I use object dBLink in base (or parent) class and I can't access to mysqli methods (dbLink member of base class): Articles class: require_once ('./includes/db.inc'); class Articles extends Database{ private $id, .... .... $visible = null; public function __construct() { // Set date as 2009-07-08 07:35:00 $this->lastUpdDate = date('Y-m-d H:i:s'); $this->creationDate = date('Y-m-d H:i:s'); } // Setter .... .... // Getter .... .... public function getArticlesByPosition($numArticles) { if ($result = $this->dbLink->query('SELECT * FROM articles ORDER BY position LIMIT '.$numArticles)) { $i = 0; while ($ret = $result->fetch_array(MYSQLI_ASSOC)) { $arts[$i] = $ret; } $result->close(); return $arts; } } } In my front page php I use article class: include_once('./includes/articles.inc'); $articlesObj = new articles(); $articles = $articlesObj->getArticlesByPosition(1); var_dump($articles); [color=]Error that go out is follow[/color] Notice: Undefined property: Articles::$dbLink in articles.inc on line 89 Fatal error: Call to a member function query() on a non-object in articles.inc on line 89 If I remove constructor on derived class Articles result don't change Please help me Hi I am trying to create a hierarchy array from our mysql database. What i have so far is: //instantiate DB & connect $database = new Database(); $db = $database->connect(); //instantiate question object $question = new Question($db); //query $results = $question->read(); //check for data if ($results) { $question_arr['questions'] = array(); $child_arr = array(); while ($row = $results->fetch(PDO::FETCH_ASSOC)) { array_push($question_arr['questions'], $row); $question_arr['questions'][] = buildTree($row); } print_r($question_arr['questions']); } else { echo json_encode(array('message'=>'nothing here!.')); } function buildTree($child) { $branch = array(); foreach ($child as $row) { $childresults = $question->read_children($row['parentid']); while ($childrow =$childresults->fetch(PDO::FETCH_ASSOC)) { $children = buildTree($childrow); if ($children) { $row['children'] = $children; } $branch[] = $childrow; } } //} return $branch; } in my Questions.php file: <?php class Question{ private $conn; public $id; public $childid; public $parentid; public $question; public $pageid; public $numclicks; public $typeid; public $date_created; // Constructor with DB public function __construct($db) { $this->conn = $db; } public function read() { //create query(sql statement) $query = 'SELECT id as parentid, question, pageid, typeid,numclicks,date_created from ct_questions'; // Prepare statement $stmt =$this->conn->prepare($query); // Execute query $stmt->execute(); return $stmt; } public function read_children($parentid) { //This is from a View I created in Mysql $query = 'SELECT parent_question, parentid, parent_pageid, child_question, childid, child_pageid from ct_vquestion_parent_child_lookup where parentid='.$parentid.''; // Prepare statement $stmt = $this->conn->prepare($query); // Execute query $stmt->execute(); return $stmt; } }
the current errors i am getting a <br /> <b>Notice</b>: Undefined variable: question in <b>C:\htdocs\api\questions\read.php</b> on line <b>41</b><br /> <br /> <b>Fatal error</b>: Uncaught Error: Call to a member function read_children() on null in C:\htdocs\api\questions\read.php:41 Stack trace: #0 C:\htdocs\api\questions\read.php(28): buildTree(Array) #1 {main} thrown in <b>C:\htdocs\api\questions\read.php</b> on line <b>41</b><br /> could anyone advice how to extend the php class who contains variable? sample below does not work. Code: [Select] class test1 extends test2($index){ public function output($index){ echo $index; } } class test2{ public function __construct($index){ echo $index; } } $test = new test1; $test->output('My Test2'); $test->test2('My Test1'); Hi Not sure if I am on the right track here but what I am trying to do is set a variable in the parent class and for this to be accessible in the child. class layout { public $site_id; function __construct($site_id) { $this->site_id = $site_id; } function get_flags() { return new flags($this); } function top_nav() { return new top_nav($this); } } class top_nav extends layout { function __construct(){ } function display_site_id() { echo $this->site_id; } } class flags extends layout { function __construct(){ } function display_site_id() { echo $this->site_id; } } $site_id = 1; $layout = new layout($site_id); $flags = $layout->get_flags(); $nav = $layout->top_nav(); var_dump($layout); var_dump($flags); var_dump($nav); This gives me the following output object(layout)#1 (1) { ["site_id"]=> int(1) } object(flags)#2 (1) { ["site_id"]=> NULL } object(top_nav)#3 (1) { ["site_id"]=> NULL } Where I would have expected object(layout)#1 (1) { ["site_id"]=> int(1) } object(flags)#2 (1) { ["site_id"]=> int(1) } object(top_nav)#3 (1) { ["site_id"]=> int(1) } but I am new to OOP and might be doing things completely wrong Thanks for your help Regards
My script has 3 classes (that are relevant to this discussion): DB, User and Validate. They are all in independent files and loaded automatically, when required, by an autoloader.
The error messages I am getting a Any pointers as to what I am doing wrong, or what I should be doing, would be most welcome. Hello. i have some code that works with out using parent and child but i dont think im doing it in the correct oop way. would someone maybe please just have a little look for me please. by the way.. i know im not ment to use global but thats how i was shown to do that on my tutorial videos.. i'll address that in another post so. in this example i have this pages class Code: [Select] <?PHP require_once(LIB_PATH.DS.'database.php'); class Pages { protected static $table_name="pages"; protected static $db_fields = array( 'id', 'pageName', 'contTemp_id', 'contElements_id', 'title', 'sub_title', 'description', 'about', 'image', 'created', 'dateMod', 'timeMod'); public $id; public $pageName; public $contTemp_id; public $contElements_id; public $title; public $sub_title; public $description; public $about; public $image; public $created; public $dateMod; public $timeMod; // "new" is a reserved word so we use "make"(or "build") public static function make( $id="", $pageName="", $contTemp_id="", $contElements_id="", $title="", $sub_title="", $description="", $about="", $image="", $created="", $dateMod="", $timeMod="") { if(!empty($title)) { $kw = new NavL3(); $kw->id = (int)$id; $kw->pageName = $pageName; $kw->contTemp_id = (int)$contTemp_id; $kw->contElements_id = (int)$contElements_id; $kw->title = $title; $kw->sub_title = $sub_title; $kw->description = $description; $kw->about = $about; $kw->image = $image; $kw->created = $created; $kw->dateMod = $dateMod; $kw->timeMod = $timeMod; return $kw; }else{ return false; } } //end function make public static function find_by_pageName($id){ global $database; $sql = "SELECT * FROM ".self::$table_name." WHERE id='".$database->escape_value($id)."'"; $result_array = self::find_by_sql($sql); return !empty($result_array) ? array_shift($result_array) : false; } public static function find_by_pageID($pageID=0){ global $database; $sql = "SELECT * FROM ".self::$table_name." WHERE id=".$database->escape_value($pageID)." LIMIT 1"; $result_array = self::find_by_sql($sql); return !empty($result_array) ? array_shift($result_array) : false; } // Common Database Methods public static function find_all(){ global $database; $sql = "SELECT * FROM ".self::$table_name.""; return self::find_by_sql($sql); } public static function find_by_id($id=0){ global $database; $sql = "SELECT * FROM ".self::$table_name." WHERE id=".$database->escape_value($id)." LIMIT 1"; $result_array = self::find_by_sql($sql); return !empty($result_array) ? array_shift($result_array) : false; } public static function find_by_sql($sql){ global $database; $results_set = $database->query($sql); $object_array = array(); while($row = $database->fetch_array($results_set)){ $object_array[] = self::instantiate($row); } return $object_array; } public static function count_all(){ global $database; $sql = "SELECT COUNT(*) FROM ".self::$table_name; $results_set = $database->query($sql); $row = $database->fetch_array($results_set); return array_shift($row); } public static function instantiate($result){ $object = new self; foreach($result as $attribute => $value){ if($object->has_attribute($attribute)){ $object->$attribute = $value; } } return $object; } private function has_attribute($attribute){ $object_vars = $this->attributes(); return array_key_exists($attribute, $object_vars); } protected function attributes(){ $attributes = array(); foreach(self::$db_fields as $field){ if(property_exists($this, $field)){ $attributes[$field] = $this->$field; } } return $attributes; } protected function sanitized_attributes(){ global $database; $clean_attributes = array(); foreach($this->attributes() as $key => $value){ $clean_attributes[$key] = $database->escape_value($value); } return $clean_attributes; } public function save(){ return !empty($this->id) ? $this->update() : $this->create(); } public function create(){ global $database; $attributes = $this->sanitized_attributes(); $sql = "INSERT INTO ".self::$table_name." ("; $sql .= join(", ", array_keys($attributes)); $sql .= ") VALUES ('"; $sql .= join("', '", array_values($attributes)); $sql .= "')"; if($database->query($sql)){ $this->id = $database->insert_id(); return true; }else{ return false; } } public function update(){ global $database; $attributes = $this->sanitized_attributes(); $attribute_pairs = array(); foreach($attributes as $key => $value){ $attribute_pairs[] = "{$key}='{$value}'"; } $sql = "UPDATE ".self::$table_name." SET "; $sql .= join(", ", $attribute_pairs); $sql .= " WHERE id=".$database->escape_value($this->id); $database->query($sql); return ($database->affected_rows() == 1) ? true : false; } public function delete(){ global $database; $sql = "DELETE FROM ".self::$table_name." "; $sql .= "WHERE id=".$database->escape_value($this->id); $sql .= " LIMIT 1"; $database->query($sql); return ($database->affected_rows() == 1) ? true : false; } } //end class blogs ?> and i have this conttemp class Code: [Select] <?PHP require_once(LIB_PATH.DS.'database.php'); class Conttemps { protected static $table_name="contTemps"; protected static $db_fields = array( 'id', 'name', 'created', 'dateMod', 'timeMod'); public $id; public $name; public $created; public $dateMod; public $timeMod; // "new" is a reserved word so we use "make"(or "build") public static function make( $id, $name="", $created="", $dateMod="", $timeMod="") { if(!empty($name)) { $kw = new Templates(); $kw->id = (int)$id; $kw->name = $name; $kw->created = $created; $kw->dateMod = $dateMod; $kw->timeMod = $timeMod; return $kw; }else{ return false; } } //end function make public function find_contTemp($pageID){ $page = Pages::find_by_pageID($pageID); $pageCID = $page->contTemp_id; $sql = "SELECT * FROM ".self::$table_name." WHERE id=".$pageCID.""; $result_array = self::find_by_sql($sql); return !empty($result_array) ? array_shift($result_array) : false; } // Common Database Methods public static function find_all(){ global $database; $sql = "SELECT * FROM ".self::$table_name.""; return self::find_by_sql($sql); } public static function find_by_id($id=0){ global $database; $sql = "SELECT * FROM ".self::$table_name." WHERE id=".$database->escape_value($id)." LIMIT 1"; $result_array = self::find_by_sql($sql); return !empty($result_array) ? array_shift($result_array) : false; } public static function find_by_sql($sql){ global $database; $results_set = $database->query($sql); $object_array = array(); while($row = $database->fetch_array($results_set)){ $object_array[] = self::instantiate($row); } return $object_array; } public static function count_all(){ global $database; $sql = "SELECT COUNT(*) FROM ".self::$table_name; $results_set = $database->query($sql); $row = $database->fetch_array($results_set); return array_shift($row); } public static function instantiate($result){ $object = new self; foreach($result as $attribute => $value){ if($object->has_attribute($attribute)){ $object->$attribute = $value; } } return $object; } private function has_attribute($attribute){ $object_vars = $this->attributes(); return array_key_exists($attribute, $object_vars); } protected function attributes(){ $attributes = array(); foreach(self::$db_fields as $field){ if(property_exists($this, $field)){ $attributes[$field] = $this->$field; } } return $attributes; } protected function sanitized_attributes(){ global $database; $clean_attributes = array(); foreach($this->attributes() as $key => $value){ $clean_attributes[$key] = $database->escape_value($value); } return $clean_attributes; } public function save(){ return !empty($this->id) ? $this->update() : $this->create(); } public function create(){ global $database; $attributes = $this->sanitized_attributes(); $sql = "INSERT INTO ".self::$table_name." ("; $sql .= join(", ", array_keys($attributes)); $sql .= ") VALUES ('"; $sql .= join("', '", array_values($attributes)); $sql .= "')"; if($database->query($sql)){ $this->id = $database->insert_id(); return true; }else{ return false; } } public function update(){ global $database; $attributes = $this->sanitized_attributes(); $attribute_pairs = array(); foreach($attributes as $key => $value){ $attribute_pairs[] = "{$key}='{$value}'"; } $sql = "UPDATE ".self::$table_name." SET "; $sql .= join(", ", $attribute_pairs); $sql .= " WHERE id=".$database->escape_value($this->id); $database->query($sql); return ($database->affected_rows() == 1) ? true : false; } public function delete(){ global $database; $sql = "DELETE FROM ".self::$table_name." "; $sql .= "WHERE id=".$database->escape_value($this->id); $sql .= " LIMIT 1"; $database->query($sql); return ($database->affected_rows() == 1) ? true : false; } } //end class blogs ?> the bit im interested in is this function in the Conttemp class Code: [Select] public function find_contTemp($pageID){ $page = Pages::find_by_pageID($pageID); $pageCID = $page->contTemp_id; $sql = "SELECT * FROM ".self::$table_name." WHERE id=".$pageCID.""; $result_array = self::find_by_sql($sql); return !empty($result_array) ? array_shift($result_array) : false; } it call a function in from the Pages class. i could take the function from here and put it in the Pages class i guess but i was wondering about Exends. should i do class Conttemps extends Pages { and use something like Code: [Select] public function find_contTemp($pageID){ $pageCID= Pages::contTemp_id; $sql = "SELECT * FROM ".self::$table_name." WHERE id=".$pageCID.""; $result_array = self::find_by_sql($sql); return !empty($result_array) ? array_shift($result_array) : false; } i guess that wont work because its not getting the $pageID but anyway.. any thoughts ???? thanks rick I have one table but i try to make like the result not finished.
Hmm.. can you see my table :
FireShot Screen Capture #003 - 'localhost _ 127_0_0_1 _ pmis_dbase _ rekening_kegiatan I phpMyAdmin 4_0_4_1' - localhost_phpmyadmin_index_php_db=pmis_dbase&table=rekening_kegiatan&target=sql_php&token=93960ef7b5.png 803.36KB
0 downloads
I want to declare sum for parent kd_rekening in same row for "Anggaran" => jns_anggaran =1 and "Perubahan" => jns_anggaran = 2. And child ust load field nilai. Untitled.jpg 34.7KB 0 downloads Thanks before If a class has a constructor but also has a static method, if I call the static method does the constructor run so that I can use an output from the constructor in my static method? --Kenoli Hi Can you call Class A's methods or properties from Class B's methods? Thanks. Ok. I know you can pass the object of a class as an argument. Example: class A { function test() { echo "This is TEST from class A"; } } class B { function __construct( $obj ) { $this->a = $obj; } function test() { $this->a->test(); } } Then you could do: $a = new A(); $b = new B($a); Ok so that's one way i know of. I also thought that you could make a method static, and do this: (assuming class A's test is 'static') class B { function test() { A::test(); } } But that is not working. I'd like to know all possible ways of accomplishing this. Any hints are appreciated. thanks I have a major problem; I have two tables - Category and Product The catID is the primary key for Category and acts as the foreign key for Product. I have some example data below; CATEGORY catID: 3 cat: Pink PRODUCT prodID: 1 product: Fuchsia catID: 3 prodID: 2 product: Dark Pink catID: 3 what I want is the page to display the data like this? Header: Pink Content: Fuchsia Dark Pink Below is the code thus far; Code: [Select] <?php error_reporting(E_ALL ^ E_NOTICE); ini_set("display_errors", 1); require ('includes/config.inc.php'); include ('./includes/header.html'); require (MYSQL); include ('./includes/main.html'); if($id = isset($_GET['catID'])) { $q = ('SELECT `category`.`catID` , `category`.`cat` , `product`.`product` FROM `product` LEFT JOIN `hairext`.`category` ON `product`.`catID` = `category`.`catID` WHERE `product`.`catID`="'.$_GET['catID'].'"'); $r = mysqli_query($dbc, $q); echo '<div id="right">'; $num = mysqli_num_rows($r); for ($j = 0 ; $j < $num ; ++$j) { $row = mysqli_fetch_row($r); echo '<h1>' . $row[1] . '</h1>'; } while($row = mysqli_fetch_array($r)) { echo '<p>'; echo $row[2]; echo "<br />"; echo '</p>'; } echo '</div>'; } include ('./includes/footer.html'); ?> At the moment, this is not doing what I want, I apologise if this is very long winded, but how do I solve this problem please? Ok, here is the whole code for the downline, but the problem is that it doesn't show members below that one I mean if b follows a, and c follows b and I opened the page of A, it will only show A's info, and not bring B and C in the downline Code: [Select] <?php if($_REQUEST["i"]){ GenerateTree($_REQUEST["i"]); } else{ GenerateTree($_GET['id']); } function GenerateTree($memberid){ $l1="<img src='icon.gif' width='33' height='45' alt='No Record' longdesc='#' />";$l2="<img src='icon.gif' width='33' height='45' alt='No Record' longdesc='#' />"; $query = "SELECT * FROM users where recruiteris='".$memberid."' order by type"; //echo $query; $result = mysql_query($query); //var_dump($result); while ($row = mysql_fetch_array($result, MYSQL_BOTH)) { if($row["type"]=="Company"){$l1=getDownline($row["id"]);} if($row["type"]=="client"){$l2=getDownline($row["id"]);} } mysql_free_result($result); echo "<table border='0' class='mainTable' cellspacing='0' cellpadding='3' style='width:100%'>\n"; echo "<tr><td colspan='3' style='text-align:center;'>Login ID: ".$memberid.getInfo($memberid)."<br />"."</td></tr>"; echo "<tr><td colspan='3'>".getDownline($memberid)."</td></tr>"; echo "<tr><td style='width:33%;'>".$l1."</td><td style='width:33%;'>".$l2."</td>"; echo "</table>\n"; } function getDownline($memberid){ $query = "SELECT * FROM users where recruiteris='".$memberid."' order by type"; //echo $query; $result = mysql_query($query); //var_dump($result); $final = "<table border='0' style='width:100%;' class='internalTable' cellspacing='0' cellpadding='2'>\n"; $final .= "<tr>"; $nothing=true; $x=0; $pre; while ($row = mysql_fetch_array($result, MYSQL_BOTH)) { $x++; $_SESSION['s']=0; if($row["type"]=="Company" && $x==1){$final .= "<td style='width:33%; background-color:#FFFFEC;' title='".getToolTip($row["login_id"])."'><a href='gen.php?i=".$row["login_id"]."'>".$row["login_id"]."</a><br />".$row["m_name"]."<br />Position: ".$row["form_type"]."<br />Downline - ".getCount($row["login_id"]).$_SESSION['s']."</td>";} if($row["type"]=="client" && $x==2){$final .= "<td style='width:33%; background-color:#E1F0FF;' title='".getToolTip($row["login_id"])."'><a href='gen.php?i=".$row["login_id"]."'>".$row["login_id"]."</a><br />".$row["m_name"]."<br />Position: ".$row["form_type"]."<br />Downline - ".getCount($row["login_id"]).$_SESSION['s']."</td>";} if($row["type"]=="client" && $x==1){$final .= "<td style='width:33%'><img src='icon.gif' width='33' height='45' alt='No Record' longdesc='#' /></td><td style='width:33%; background-color:#E1F0FF' title='".getToolTip($row["login_id"])."'><a href='gen.php?i=".$row["login_id"]."'>".$row["login_id"]."</a><br />".$row["m_name"]."<br />Position: ".$row["form_type"]."<br />Downline - ".getCount($row["login_id"]).$_SESSION['s']."</td>";} $pre = $row["type"]; $nothing=false; } if($nothing){$final .= "<td style='width:33%'><img src='icon.gif' width='33' height='45' alt='No Record' longdesc='#' /></td><td style='width:34%'><img src='icon.gif' width='33' height='45' alt='No Record' longdesc='#' /></td>"; } if($x==1 && $pre=="Company"){$final .= "<td style='width:33%'><img src='icon.gif' width='33' height='45' alt='No Record' longdesc='#' /></td>";} mysql_free_result($result); $final .= "</tr>"; $final .= "</table>\n"; return $final; } function getToolTip($id){ $query = "SELECT * FROM users where id ='".$id."'"; $result = mysql_query($query); $res; while ($row = mysql_fetch_array($result, MYSQL_BOTH)) { $res = "fade=[off] cssheader=[toolHeader] cssbody=[toolBody] header=[Detail For ID () - ".$id."] body=[".$row["m_name"]."<br />Address:<br />".$row["address"]."]"; } mysql_free_result($result); return $res; } function getInfo($id){ $query = "SELECT * FROM users where id='".$id."'"; $result = mysql_query($query); $res; while ($row = mysql_fetch_array($result, MYSQL_BOTH)) { $res = "<br />Name: ".$row["fname"]."<br />National ID: ".$row["nid"]."<br />"; } mysql_free_result($result); return $res; } function getCount($id){ $query = "SELECT * FROM users where recruiteris='".$id."'"; $result = mysql_query($query); $count = mysql_num_rows($result); $_SESSION['s'] = $_SESSION['s']+$count; while ($row = mysql_fetch_array($result, MYSQL_BOTH)) { getCount($row["id"]); } mysql_free_result($result); //echo $count."<br />"; return ""; } // Closing connection mysql_close($link); ?> Code: [Select] Main Object ( [Visitor] = Visitor Object ( [user_info] => Array ( [username] = user [user_id] = 1 ) ) [Room] = Room Object ( [info] = Array( [id] = 1 [name] = Lobby ) [messages] = Messages Object ( [messages] = Array ( [0] = Array() ) ) ) ) Is there a way to get the visitor info within the Messages Object? I'm building it such as $Main = new Main; $Main->Visitor = new Visitor; $Main->Room = new Room; $Main->Room->Messages = new Messages; so they're not static I know that I can pass the $this var through each but that duplicates the class each time and I'm 99% sure that's bad. Why won't my unset remove the array from the parent $data[0] array? Code: [Select] foreach ($data[0] as $k => $r) { if (($r['feedid'] !== $user_info['uid']) && ($r['action_id'] == 'newuser')) { unset($data[0][$k]); } } class Database { // actual database interaction // also uses mysql_real_escape etc. } class Users extends Database { function checkIfUsernameExists() { } } class addUser extends Users { // perform all add user stuff } class searchUser extends Users { // all search user stuff } So, to add a new user, I would instantiate, then perform various queries to the addUser class, probably also using the checkIfUsernameExists method in the Users class. Finally, Database would add the record. Question: what do I instantiate? Do I instantiate just the addUser one, or first the Database class? I know how to do it, but what about instantiation, using parent:: self:: etc. etc. (how do I link these clasess together is what I think I mean). I'm pulling a list of topics from my DB and they are structured hierarchally using the typical id | parent_id scheme The array I end up with from the DB is one large one with keys representing the unique id of each data result...The problem is getting past the 2d scope of the array. I know this will require a recursive function and I've been at it for hours but can't seem to wrap my hurting head around it! How do I get my orignal array in this form: Array ( [0] => Array ( [1] => top parent [2] => top parent [3] => top parent [9] => top parent ) [2] => Array ( [4] => #1 child of 2 [5] => #2 child of 2 ) [3] => Array ( [6] => #1 child of 3 ) [4] => Array ( [7] => #1 child(subsub) of 4 [8] => #2 child(subsub) of 4 ) ) To look something more like this? : Array ( [1] => top parent [2] => Array ( [4] => Array ( [7] => #1 child(subsub) of 4 [8] => #2 child(subsub) of 4 ) [5] => #2 child of 2 ) [3] => Array ( [6] => #1 child of 3 ) [9] => top parent ) notice how the 2nd array has all the proper dimensions according the the DB hierarchy. Thank you ps. or maybe I should work from a different array to start from...I'm open to suggestions This topic has been moved to PHP Applications. http://www.phpfreaks.com/forums/index.php?topic=356195.0 Mmm i'm not sure if i'm approaching this correctly. Anyways, I wanted to create a multi-level thread, Where the child thread would be after the parent thread. Something like this: Hello World - Hello World - Hi! - What's up? - Hi Bob! Goodbye World - ....This guy got issues - Dude! You should watch Despicable Me! "It's so fuzzy i'm going to dieee!" Anyways, so my table looks something along the line of this: | post id | parent_id | title | body | date | 1 | NULL | Hello | Hi, i'm K | date 2 | NULL | Thread One | Body One | date 3 | 1 | Hello World | Body One | date 4 | 2 | Thread post 4 | Body One | date 5 | 1 | Thread post 5 | Body One | date 6 | 1 | Thread post 6 | Body One | date 7 | 3 | Hi What's up | Body One | date And here's the PHP code, although it's not very neat I want to clean it up and make it neater. I can only go two level deep so far. Any suggestion or recommendations? Using while & for: // Select * Threads $q = "SELECT * FROM test_db ORDER BY post_id ASC"; $r = @mysql_query($q); while ($pid_row = @mysql_fetch_object($r)) { // Array $pid_arr[] = $pid_row->post_id; // Assign Indexes to Post ID $ppid_arr[] = $pid_row->parent_id; // Assign Indexes to ParentID $md_arr = array($pid_arr, $ppid_arr); // Create multi-dimensional array matrix $parent_id = $pid_row->parent_id; } for ($i = 0; $i < count($pid_arr); $i++) { for ($a = 0; $a < count($ppid_arr); $a++) { $pid = $pid_arr[$i]; // pid = post id $ppid = $ppid_arr[$i]; // ppid = parent id //echo "<div>~~ PID $pid ~~ PPID $ppid ~~</div>"; if ($ppid === NULL) { $ppid_is_null = " & parent_id is NULL"; } else { $ppid_is_null = NULL; } // Select Top level Thread $z = "SELECT * FROM test_db WHERE post_id = '$pid'"; $y = @mysql_query($z); while ($t_row = @mysql_fetch_object($y)) { $title = $t_row->title; // title of child thread $level = $t_row->level; // level of child thread...is this useful? } // Display top level thread lvl 1 if ($ppid === NULL) { // If the parent_id is NULL, display top level thread echo '<div>PID: ' . $pid . ' || PPID: ' . $ppid . " || Title: " . $title . "</div><br>\n"; $post = $pid; // PostID = 1 $parent = $ppid; // Parent ID ex: [1] // Get child id, where parent id = [1] // trying to get the child thread here...but it's not working $child_q = "SELECT * FROM test_db WHERE parent_id = '$post'"; $child_r = @mysql_query($child_q); while($c_row = @mysql_fetch_object($child_r)) { $c_arr[] = $c_row->post_id; $c_ppid_arr[] = $c_row->parent_id; } for ($n = 0; $n < count($c_arr); $n++) { if ($c_ppid_arr[$n] === $post) { echo "<div>$c_arr[$n]</div>"; } } break; //echo "<div>PID: $pid</div>"; } break; } } Using While: <?php require_once('db_connection'); echo '<hr><hr><br>'; // I just realized that selecting * where parent id is null might limit the amount of rows retrieved. // Query to select threads $n = NULL; $q = "SELECT * FROM test_db WHERE (test_db.parent_id is NULL) Order By date ASC"; $r = @mysql_query($q); while ($threads = @mysql_fetch_object($r)){ $pid = $threads->post_id; $sid = $threads->subject_id; $parent_id = $threads->parent_id; $title = $threads->title; $body = $threads->body; echo '<div>PostID: ' . $pid . ' || Parent: ' . $parent_id . ' || SubjectID: ' . $sid . ' || Title: ' . $title . ' || Body: ' . $body . '</div>'; $q2 = "SELECT * FROM test_db WHERE parent_id = '$pid' Order by date DESC"; $r2 = @mysql_query($q2); while ($level2 = @mysql_fetch_object($r2)) { $level2_pid = $level2->post_id; $level = 1.5 *($level2->level); // lvl 2: 3em echo '<div style="text-indent:' . $level . 'em">' . 'PostID: ' . $level2->post_id . ' || ParentID: ' . $level2->parent_id . '</div>'; $q3 = "SELECT * FROM test_db WHERE parent_id = '$level2_pid'"; $r3 = @mysql_query($r3); while ($level3 = @mysql_fetch_object($r3)) { $level3 = 1.5 + $level; echo '<div style="text-indent:' . $level3 . 'em">' . 'PostID: ' . $level3->post_id . ' || ParentID: ' . $level3->parent_id . '</div>'; } } } ?> I'm not a comp. sci major or anything, so I'm learning this as I go. Any help would be greatly appreciated. It seems like the while & for is more practical, but i'm not quiet sure. What am I doing wrong? - K I just joined this forum today ^_^ Hope to be good friends with you guys and gals |