PHP - Problem With Derived Class
I have the code as given below:
<?php class ABC { function printValue() { print("This value shall be printed" . $this->x); } } class BCD extends ABC { private $x=10; } $bcd=new BCD; $bcd->printValue(); ?> But when I try to access printValue function from the paren class it gives me error... Fatal error: Cannot access private property BCD::$x in /var/www/html/trainingweb/modules/test/TestAtitProblem.php on line 5 As the public method of ABC would be extended to BCD, it shall have access to its own member. please help... Similar TutorialsI 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 want to store files to variable array using glob() like $files[0] = xyz.txt $files[1] = pqr.txt . . . $files[n] = nfile.txt I know how to list files from directory using glob() Code: [Select] <?php foreach (glob("*.txt") as $filename) { echo "$filename size " . filesize($filename) . "\n"; } ?> How can I do that ? class Z { function foo() { // do somethig } } class X { $x function __contruct() { $this->x = new z(); } function var() { $this->x->foo(); // Fatal error: Using $this when not in object contex } } // Class declaration here class Y { function __contruct() { $z = new z(); $x = new x(); } } Hi, this php code not working for some reason Code: [Select] class db { public function connect() { $yhteys = new PDO("mysql:host=*****;dbname=*****", "*******", "******"); } public function get($query, $parameters){ $prepare = $yhteys->prepare($query); $prepare->execute($parameters); $result = $prepare->fetch(); $count = $prepare->rowCount(); return array($result, $count); } } Code: [Select] $db = new db(); $content = $db->get("SELECT * FROM tuotteet WHERE id = ?", array("1")); print $content; It gives error:Parse error: syntax error, unexpected T_OBJECT_OPERATOR Thank you for help! Hey guys! I have spent the last 5 and a half hours banging my head up against the wall trying to fix this to no avail so I guess its time to ask the experts!!! I am having a problem with my membership class. Basically, it works perfectly if a user logs in using sessions and not cookies. But when remember is set to 1 (they ticked the remember me checkbox), the mysql query fails on this line when we run $member_class->member_class(); Code: [Select] $result = mysql_fetch_array(mysql_query("SELECT * FROM members WHERE email = '{$email}' AND token ='{$token}' AND ip_address LIKE '{$ip_address}%'"), MYSQL_ASSOC) or DIE ($this->query_error); Everything matches up except for the $token value. Basicly I believe that a new token is updated in the mysql database, before the token value in the cookie is updated as when I print $token, it definitly matches up with the token value in the mysql database. But from reading through the code, it all looks perfectly fine to me which is why i am so confused. If i change $newtoken = $this->token(); // generate a new token to $newtoken = '1234'; the script also works perfectly fine without errors (though not very secure so would like the token to change values! Really appreciate any input! Cheers <?php // member class // handlers member logon class member_class { var $message = ''; var $query_error = 'ERROR: something went wrong when accessing the database. Please consult your webmaster'; function member_class() { //constructor if (!$_SESSION['member_id']) { //fills session with empty values $this->set_session_defaults();; } if ($_SESSION['logged_in']) { //already logged in $this->check_session(); } if ($_COOKIE['remember']) { $this->check_remembered($_COOKIE['remember']); } } function check_login($email,$password,$remember,$redirect) { $email = mysql_escape_string($email); $salt='s+(_v'; $password = mysql_escape_string(hash('sha512', $salt . $password)); $result=mysql_fetch_array(mysql_query("SELECT * FROM members WHERE email = '{$email}' AND password = '{$password}'"), MYSQL_ASSOC); if ($result) { $this->set_session($result,$remember,true); return true; } else { $this->failed = true; $this->logout(); //create error message telling user that either the email address does not exist, or they have entered the wrong password associated with the email address $result=mysql_fetch_array(mysql_query("SELECT email FROM members WHERE email = '{$email}'")); if($result) { $this->message .= 'Incorrect Password. Please try again'; } else { $this->message .= 'The email address '.$email.' does not exist. Please try again or <a href="/register.php" class=" cboxElement">create a new account</a>.'; } return false; } } function logout() { // blowup cookie setcookie('remember',time()-3600); $this->set_session_defaults(); } function set_session($result,$remember,$init = true) { $member_id=$result['member_id']; if ($init) { $session = mysql_escape_string(session_id()); $ip_address = mysql_escape_string($_SERVER['REMOTE_ADDR']); $newtoken = $this->token(); // generate a new token // generate a random token $update = mysql_query("UPDATE members SET session='{$session}', token='{$newtoken}', ip_address='{$ip_address}' WHERE member_id='{$member_id}'") or DIE ($this->query_error); } $_SESSION['member_id'] = $result['member_id']; $_SESSION['email'] = htmlspecialchars($result['email']); $_SESSION['fullname'] = $result['fullname']; $_SESSION['token'] = $newtoken; $_SESSION['logged_in'] = true; if ($remember) { $this->update_cookie($newtoken); } } function update_cookie($token) { $cookie = serialize(array($_SESSION['email'],$token)); //print $token; setcookie('remember',$cookie, time()+12099600); } function check_remembered($cookie) { $serializedArray=$cookie; $serializedArray = stripslashes($serializedArray); list($email,$token) = unserialize($serializedArray); if(empty($email) or empty($token)) { return; } else { $email = mysql_escape_string($email); $token = mysql_escape_string($token); $ip_address = mysql_escape_string($_SERVER['REMOTE_ADDR']); //changed from = '{ip_address} to like '{ipaddress}% so we are not strict in ip address we only limit to first 3 charactors of ip $ip_address = substr($ip_address, 0, 3); $query = "SELECT * FROM members WHERE email = '{$email}' AND token ='{$token}' AND ip_address LIKE '{$ip_address}%'"; print $query; $result = mysql_fetch_array(mysql_query("SELECT * FROM members WHERE email = '{$email}' AND token ='{$token}' AND ip_address LIKE '{$ip_address}%'"), MYSQL_ASSOC) or DIE ($this->query_error); if (!$result) { // $this->set_session($result,false,false); }else{ $this->set_session($result,true,true); } } } function token() { // generate a random token for($i=1;$i<33;$i++) { $seed .= chr(rand(0,255)); } return md5($seed); } function check_session() { $email = mysql_escape_string($_SESSION['email']); $token = mysql_escape_string($_SESSION['token']); $session = mysql_escape_string(session_id()); //if ip address changes it will fail POSSIBLY DO NOT NEED THIS! $ip_address = mysql_escape_string($_SERVER['REMOTE_ADDR']); //check only the first 4 charactors of ip address incase user changes ip in corporate workplace etc ALSO CHANGED = TO LIKE IN MYSQL QUERY AND ADDEED % TO THE END AS WILDCARD $ip_address = substr($ip_address, 0, 3); $result = mysql_fetch_array(mysql_query("SELECT * FROM members WHERE email='{$email}' AND token='{$token}' AND session='{$session}' AND ip_address LIKE '{$ip_address}%'"), MYSQL_ASSOC or DIE ($this->query_error)); if ($result != false){ }else{ $this->logout(); } } }?> Hi im having trouble getting the below code to listen to my css margin settings. Just to clear up the server side of things, can anybody tell me wether or not im using the correct syntax in the code below? Code: [Select] else { echo("<p class=\"passed\">Thankyou for submiting your details, you will be added to our directory shortly</p>"); }} So... I have the following code for my rss_reader class: <?php class rss_reader { const USE_CURL = TRUE; private $_userAgent = ''; private $_url = ''; public function __construct($url, $userAgent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1') { $this->_url = $url; $this->_userAgent = $userAgent; } public function writePOST() { $postval= $this->getPOST(); echo $postval; } public function getPOST($format = '<b>%s</b>%s<i>%s</i>') { $xml = $this->getXML(); $script1 = $xml->channel->item->title; $script2 = $xml->channel->item->description; $script3 = $xml->channel->item->pubDate; return sprintf($format, $script1, $script2, $script3); } private function getXML() { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $this->_url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_USERAGENT, $this->_userAgent); curl_setopt($ch, CURLOPT_TIMEOUT ,3); $data = curl_exec($ch); curl_close($ch); return new SimpleXMLElement($data); } } Basically, atm it writes the newest post found at the RSS feed. What I wan't to do is extend this to create an array of all of the posts that I can iterate over to "write" ALL of the posts. I will then later work on a method for pagination. Atm though, I am kinda lost and don't really know where to start. Anyone know how I could accomplish this? thanks much. ps: everything else with the rss reader works as intended. I got some help from this forum previously and am having some more issues. I created a database class that works and returns a PDO object. I am having trouble figuring out how to use the object in another class I want to use to access some CRUD functions. I get to the point where I start using the pdo object I create in the database class and my code fails. I am obviously calling the pdo object property incorrectly. I guess I don't understand the proper syntax. I've included the code for the database class and the CRUD class. The problem starts at the point where I try to run a prepared statement. I have include a comment "Problem stars here" to indicate that point. There is a lot of debug stuff still in the code. Thanks, --Kenoli <?php class Db { public $pdo = ''; public $message = 'A message from db!<br><br>'; function __construct() { $servername = "localhost"; $username = "root"; $password = ""; $dbname = "tio-local"; $db_options = array( PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC ); try { $this->pdo = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password, $db_options); // set the PDO error mode to exception $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } // End Try catch(PDOException $e) { echo "Error: " . $e->getMessage(); } } // End __construct } // End class definition DB.php $db = new Db; $pdo = $db->pdo; print_r ($pdo); ?> <?php // Db_functions.php include_once ('Db.php'); // $db instantiated in class file $pdo = $db->pdo; class Db_functions { public $pdo = ''; function __construct($pdo) { $this->pdo = $pdo; } // Close __construct public function insert($table_name, $white_list, $insert_array) { if ($white_list == '' && $table_name == 'Sites') { $white_list = array('gone'=>'','site_name' =>'', 'site_address' =>'', 'grommets' =>'', 'tape' =>'', 'site_image' =>'', 'description' =>'', 'surface' =>'', 'tio_contact' =>'', 'site_contact' =>'','owner' =>'', 'lessee' =>'', 'contact_phone' =>'', 'contact_email' =>'', 'contact_date' =>'', 'comments' =>''); } elseif ($white_list == '' && $table_name == 'Persons') { $white_list = array('gone'=>'', 'fname'=>'', 'lname'=>'', 'tio'=>'', 'volunteer'=>'', 'general'=>'', 'artist_pic'=>'', 'email'=>'', 'website'=>'', 'telephone'=>'', 'address'=>'', 'city'=>'', 'state'=>'', 'zip'=>'', 'statement'=>''); } echo '<strong>***The following is the PDO object: </strong>'; print_r ($this->pdo); echo '<p>The following is the $white_list:<br>'; echo '<pre>'; print_r ($white_list); echo '</pre>'; echo '<strong>***The following is the PDO object: </strong>'; print_r ($this->pdo); /** Test and remove any unpermitted columns **/ $insert_array = array_intersect_key($insert_array, $white_list); echo '<strong>***The following is the PDO object: </strong>'; print_r ($this->pdo); /** Generate variables to create prepared statements **/ foreach($insert_array as $key => $value) { $col .= $key . ', '; $val .= ':' .$key . ', '; } echo '$col = ' . $col . '<p>'; echo '$val = ' . $val . '<p>'; echo '<strong>***The following is the PDO object: </strong>'; print_r ($this->pdo); /** Remove ', ' at end of arrays and create prepared statement */ $col = substr_replace($col ,"",-2); $val = substr_replace($val ,"",-2); $sql = "INSERT INTO Sites ($col) VALUES ($val)"; echo "<p>SQL = $sql<br><br>"; /** Debug **/ echo '<h3>More</h3<br>'; /** Register prepared statement */ /****** PROBLEM STARTS HERE *****/ $stmt = $this->pdo->prepare($sql); echo '<h3>More2</h3>'; /** Create [:field, $value] pairs. */ foreach($insert_array as $key => $value) { $param = ':' . $key; $stmt->bindParam($param, $$value); //} /** Create [field => value] array */ foreach($insert_array as $key => $value) { $insert[$key] = $value; } /** Execute statement using $insert array. **/ $stmt->execute($insert); } // End insert function } // Close class definition $db_functions = new Db_functions($pdo); $insert_array = array('fname' => 'John', 'lname' => 'Hancock'); $db_functions->insert('Persons', '', $insert_array); echo '<pre>'; print_r ($db_functions); echo '</pre>'; ?> Edited February 6 by kenoli Well i have this set of codes <?php include "includes/config.php"; class template{ var $page; var $built; public $block = array(); function _start($tpl){ $this->page = $tpl; } function set_array($data){ $this->block[] = $data; } function _show(){ foreach($this->block as $k => $v){ foreach($v as $k1 => $v1){ //echo $k1."<br />"; //echo $v1."<br />"; $this->page = str_replace("{".$k1."}", $v1, $this->page); } } echo $this->page; } } $template = new template(); $file = "<html> <body> <p>{CAT}</p> <p>{SUBCAT}</p> </body> </html>"; $template->_start($file); // Category Query while($row1 = mysql_fetch_assoc($cat)){ $template->set_array(array("CAT" => $row1['title'])); // Sub Category Query while($row2 = mysql_fetch_assoc($subcat)){ $template->set_array(array("SUBCAT" => $row2['title'])); } } $template->_show(); ?> Now, when i echo $k1 or $v1 they display the keys and values in the correct order like CAT1 SUBCAT1.1 SUBCAT1.2 CAT2 SUBCAT2.1 SUBCAT2.2 but when it goes through the str_replace its only displays the CAT1 and SUBCAT1.2 what going wrong? this code doesn't work, why? define("DIR", "../../"); final class MyClass { private static $PATH = DIR . '../directory/'; } Hey guys im just starting to use Prepared Statements in php and i am trying to build a search but i have come across a problem. Hope someone can help or point me to more information on how to resolves this. Ok here is the code below:: public function search($string) { if(strlen($string) > 40) { return "Woow too many words, please shorten your search."; } if(empty($string)) { return "I'm a search, you type things in and I find. Please enter something and try again!"; } if(strlen($string) <= 3) { return "Come on dude, you expect me to find summin with that? Type some more tags in!"; } $x=0; // Teh string could be multiple searches so explode:: $string = explode(" ", $string); foreach($string as $search) { $x++; if($x == 1) { @$sql .= "(blog_tags LIKE '%$search%')"; } else { @$sql .= " OR (blog_tags LIKE '%$search%')"; } } $sql = "SELECT blog_tags FROM subarc_blog WHERE $sql LIMIT 40"; // TODO:: Count how many search results found:: $stmt = $this->conn->prepare($sql); $stmt->execute(); $stmt->bind_result($search); Ok by using the bind_result() i need to know how many result are being returned to add them to a variable is this correct ? if so how can i tell how many results have been returned ? hope this makes sense hey guys i have a script ive made which loads classes automatically when called...the script works fine but when i extend the class Autoloader_Exception and it comes back with the error Code: [Select] Fatal error: Class 'Autoloader_Exception' not found in C:\www\library\autoloader.class.php on line 3 i might be missing something here but i dont know why the autoloader doesnt load the extended class if someone can please help me how i can extend the class please thanks Code: [Select] <?php class Autoloader extends Autoloader_Exception { protected static $_declared_classes = array(); public static function load_class($class_name) { $class_name = ucwords($class_name); $file = self::get_class_path($class_name); try { if (!class_exists($class_name, FALSE)) { if (file_exists($file)) { require_once $file; self::$_declared_classes[] = $class_name; } else { throw new Exception(sprintf("Class '%s' not found.<br />\n", $class_name)); } } } catch (Exception $e) { echo $e->getMessage(); } } protected static function get_class_path($class_name) { global $classes; if (array_key_exists($class_name, $classes)) { return ROOT . DS . $classes[$class_name]; } } public static function declared_classes() { echo "<pre>"; print_r(self::$_declared_classes); echo "</pre>"; } } spl_autoload_register(array('Autoloader', 'load_class')); ?> Hi... I have query in highlighting null data using this code: Code: [Select] <?php include 'config.php'; $currentEmpID = $_SESSION['empID']; if(!isset($_POST['Regsubmit_'])){ $DATE1 = $_GET['Regfirstinput']; $DATE2 = $_GET['Regsecondinput']; $sql = "SELECT DISTINCT IF(ISNULL(a.LOG_IN), 'rdc', '') AS LOGIN_CLASS, IF(ISNULL(a.LOG_OUT), 'rdc', '') AS LOGOUT_CLASS, a.EMP_ID, CONCAT(LASTNAME, ', ' , FIRSTNAME) AS FULLNAME, a.LOG_IN, a.LOG_OUT FROM $ATTENDANCE.attendance_build AS a JOIN $ADODB_DB.employment em ON (a.EMP_ID = em.EMP_NO AND em.STATUS IN ('Reg Operatives', 'Reg Staff')) WHERE LOG_IN BETWEEN '$DATE1' AND '$DATE2' OR ISNULL(LOG_IN) OR ISNULL(LOG_OUT)"; $DTR = $conn3->GetAll($sql); $smarty->assign('attendance', $DTR); } $smarty->display('header_att.tpl'); $smarty->display('RegAttendance.tpl'); $smarty->display('footer.tpl'); ?> and here is the tpl code: Code: [Select] {section name=att loop=$attendance} <tr> <td colspan="2">{$attendance[att].EMP_ID}</td> <td colspan="2">{$attendance[att].FULLNAME}</td> <td colspan="2" class="{$attendance[att].LOGIN_CLASS}">{$attendance[att].LOG_IN|date_format:"%d-%m-%Y %I:%M %p"}</td> <td colspan="2" class="{$attendance[att].LOGOUT_CLASS}">{$attendance[att].LOG_OUT|date_format:"%d-%m-%Y %I:%M %p"}</td> </tr> {sectionelse} <tr><td colspan="1">No DATA</td></tr> {/section} this code highlight the null value of login or logout or both. this is the css: Code: [Select] .rdc {background-color:#ff0000;} Now, I need to revised my query statement, because i have separate code for adding attendance if the employee has no attendance or no login or no logout. I just want to happen is if the employee is already add his attendance in NRS table or should I said if the LOG_IN in attendance table is equal to TIME_IN in NRS table the data will have a color yellow. For Example: I have this data in attendance table: EMP_ID = 012012 LOG_IN = NULL LOG_OUT = 2011-12-12 13:35:00 I will his attendance in NRS table to have his attendance: EMP_NO = 012012 TIME_IN = 2011-12-12 05:35:00 TIME_OUT = 2011-12-12 13:35:00 In my above query the LOG_IN has a background color of RED. I want to happen is if I add his attendance in NRS the EMP_NO, LOG_IN, LOGOUT will have a color to notice that it is already have in NRS. Because theirs a scenario that the employee has no login or no logout or both. Feel free to ask me if my explanation is not clear to you. Thank you in advance 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. I have an existing instance of my class Database, now I want to call that instance in my Session class, how would I go about doing this? 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 Hi, I need to be able to call a class based on variables. E.G. I would normally do: Code: [Select] $action = new pattern1() but i would like to be able to do it dynamicaly: Code: [Select] $patNum = 1; $action = new pattern.$patNum.() Im wondering if that's possible? If so what would the correct syntax be? Many Thanks. I have two classes: ## Admin.php <?php class Admin { public function __construct() { include("Config.php"); } /** * deletes a client * @returns true or false */ function deleteClient($id) { return mysql_query("DELETE FROM usernames WHERE id = '$id'"); } } ?> ## Projects.php <?php class Projects { public function __construct() { include("Config.php"); $this->admin = $admin; $this->dataFolder = $dataFolder; } /** * Deletes a project * @returns true or false */ function deleteProject($id) { $root = $_SERVER['DOCUMENT_ROOT']; $theDir = $root . $this->dataFolder; $sql = mysql_query("SELECT * FROM projectData WHERE proj_id = '$id'"); while ($row = mysql_fetch_array($sql)) { $mainFile = $row['path']; $thumb = $row['thumbnail']; if ($thumb != 'null') { unlink($theDir . "/" . substr($thumb,13)); } unlink($theDir . "/" . substr($mainFile,13)); } $delete = mysql_query("DELETE FROM projectData WHERE proj_id = '$id'"); $getDir = mysql_query("SELECT proj_path FROM projects WHERE id = '$id'"); $res = mysql_fetch_array($getDir); rmdir($theDir . "/" . $res['proj_path']); return mysql_query("DELETE FROM projects WHERE id = '$id'"); } } ?> How can I call deleteProject() from within Admin.php? Hi people! class FirstOne{ public function FunctionOne($FirstInput){ //do stuff and output value return $value1; } } Then:- class SecondOne{ public function FunctionTwo($AnotherInput){ //do stuff and output value return $value2; } } What I want to know is this, if I want to use FunctionOne() in Class SecondOne do I do it like this:- (Assume as I have instantiated the first class using $Test = new FirstOne(); ) class SecondOne{ function SecondedFunction(){ global $Test; return $Test->FunctionOne(); } public function FunctionTwo($AnotherInput){ //do stuff and output value return $value2; } public function FunctionThree(){ //some code here $this->Test->SecondedFunction();<--I think as I can omit the $this-> reference } } My point is: Do I have to do it this way or is there way of having this done through __construct() that would negate the need for a third party function? I have a version working, I just think that it is a little convoluted in the way as I have done it, so I thought I would ask you guys. Any help/advice is appreciated. Cheers Rw |