PHP - Direct Loading Of Classes Trough A Base Class
I've been trying to solve this for a while now, but still haven't had any luck.
What I'm trying to do is this: $class = new BaseClass; $var = $class->load("subclass")->subclass_function("info"); Thanks in advance Ayon 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 I've been spending long hours learning about classes and their magic methods. I just came across a tutorial which showed a constructor like this:
class Device { //... public function __construct(Battery $battery, $name) { // $battery can only be a valid Battery object $this->battery = $battery; $this->name = $name; // connect to the network $this->connect(); } //... }the Battery part instantly caught my attention. Here had previously made a Battery class (and a more complete Device class) but the next thing he did really caught my interest: $device = new Device(new Battery(), 'iMagic'); // iMagic connected echo $device->name; // iMagicwhat the hell is going on here? Is this another way to include the methods and properties of one class into another class, in order words is this the same thing as: class Device extends BatteryI don't think so because this new Battery() thing looks more like its creating an object inside the Device object. Previously the only way I could to that was to type $battery = new Battery() inside one of my methods. But this looks like hes doing something different. Can anyone explain whats going on here? The whole tutorial is he http://code.tutsplus...-php--net-13085 in the main Device method he has a premade $battery variable to hold the Battery object. Sometimes I have multiple classes containing functions which I'd like to include in my main class. I can only extend one class, so I usually extent a class containing only properties, no methods. I still don't know what difference making that info class abstract is, I'd appreciate if anyone could tell me. Also I'd love to know what the point in static methods is. I've never used them because I've never seen the point. Is it just to make it easier to call the methods because you don't need to create an object instance to call them? Sorry for the extra questions, the first one is what I'm really wondering about. HI everyone! So basically I have this class called Login and another class classed Reports. They both extend a main class called OOP. I'm trying to get classes now and in the future, when I add on, to access that class so that way I dont have to create a new object everytime I need to do that. Plus I know I dont want to rely on calling another class inside of one class. Here is an example The Super Class class OOP{ public function Login($pointer){ $Login->{$pointer}(); } public function Reports($pointer){ $Reports->{$pointer}() } } Login Class class Login extends OOP{ public function userLogin($user, $pass){ //Login code here //if error occurs, send it to Reports super::Reports(Error()); } } Reports Class class Reports extends OOP{ public function Error(){ //Send an error here } } Here is how I think I would call the class if a user was to login. $OOP = new OOP(); $OOP->Login(userLogin($user, $pass)); So now when I need to call any class I should be able to, correct? If you are confused about the top, then think of it this way: I am trying to create a class to where I can call or reference to ANY object now or in the future so I can add on and call that class from another class. Thank you for any help. I have a some value that are being generated from a database then thrown into <li><href> to create a list that user can click and fetch data through ajax right now its in a form select/menu and works fine however I need to convert to a list and use and onKeyDown event Code: [Select] <form> <select name="users" size="<?php echo $num_rows;?>" onchange="showUser(this.value)" > <?php do { ?> <option value="<?php echo $row_Recordset1['item_id']?>"><?php echo $row_Recordset1['item_id'].' '. $row_Recordset1['item_name']?></option> <?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); $rows = mysql_num_rows($Recordset1); if($rows > 0) { mysql_data_seek($Recordset1, 0); $row_Recordset1 = mysql_fetch_assoc($Recordset1); } ?> </select> </form> I need to correct this Code: [Select] <ol> <?php do { ?> <li onKeyDown="showUser(this.value)"><a href="getmenu.php?item_id="<?php echo $row_Recordset1['item_id']?>"> <?php echo $row_Recordset1['item_name']?></a></li> <?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); $rows = mysql_num_rows($Recordset1); if($rows > 0) { mysql_data_seek($Recordset1, 0); $row_Recordset1 = mysql_fetch_assoc($Recordset1); } ?> </ol> I am rebuilding a CMS system that I have been developing over the last ~6 years. It needs to have many different kinds of modules depending on the installation (Like Drupal or Joomla does) I have a Core class that does the major processing. I am currently developing the part of the system that loads the actual module into the index.php page. While experimenting I came up with an idea that is probably really horrible but I started to wonder if maybe it could actually work well. I am looking for feedback on this Core class function: Code: [Select] public function LoadMods($ModsToLoad) { foreach ($ModsToLoad as $mod) { $MainFile = ABSPATH.DS.$mod.DS.'main.php'; if (file_exists($MainFile)) include ($MainFile); else $this->_MAIN .= 'Error: The "main" file for "'.$mod.'" module could not be found<br/>'; } } It will receive an array of Module names and those names correspond to a directory that holds the "main.php" file for that module. Example: index.php?mod=Photos Will load the "Photos" module. Here is the thing that has me concerned... A module might have it's own class or classes and that class will likely get included in the "main.php" file for that module. What effect is that going to have on my core class because it starts nesting classes inside classes. Is this an efficiency advantage or am I heading down a road paved by code stink? What's you opinion? Lets say that I have an array that I want to convert to a value object My value object class is as follows: /* file UserVO.php*/ class UserVO { public $id; public $email; public function __construct($data) { $this->id = (int)$data['id']; $this->email = $data['email']; } } And I create my array of value objects as follows: /* file UserService.php*/ $array = array( array(...), array(...)); $count = count($array); for ($i = 0; $i < $count; $i++) { $result[] = new UserVO($array[$i]); } return $result; OK, so this all works fine. However, I'd like to specificy the VO that is to be created dynamically, so that I can have a single dynamic function to create my VO's. Something like: $ret = create_vo($array, 'UserVO'); function create_vo($data, $vo) { $count = count($data); for ($i = 0; $i < $count; $i++) { $result[] = new $vo($array[$i]); //this obviously wont work...Class name must be a valid object or a string } return $result; } I realise that I could do this with a switch statement (iterating through all my VO's)...but there is no doubt a much much more elegant solution. It would also be supercool if I could lazy load the VO's as needed, instead of having multiple 'includes' Any help much appreciated. hey guys im having a problem with my class it sees the constructor isnt loading and this line isnt executed Code: [Select] spl_autoload_register(array($this, 'load_class')); i dont see why not if anyone can help please Code: [Select] <?php class Autoloader { private static $_declared_classes = array(); private static $_ignore_files = array(); public function __construct() { spl_autoload_register(array($this, 'load_class')); } 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(); } } private 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>"; } ?> Not sure how to describe what I'm trying to do here in the title, but here goes with what I am trying to accomplish. I've got a few hundred lines of code in total so far, so I'll try to keep it as short as I can. I've got an application that I am programming using classes for each module and right now I am coding the base classes that I need in order for it to run (database, errors, logging, etc). What I'm doing for my database class is I have a query factory and it extends the MySQLi class so I can process, clean and code the rest of my app faster. I also have another, unrelated class "Error", which will be used for processing errors I might come across. I'd rather do it this way instead of having to call trigger_error and error_log every time there is an error. I'd also not like to have to call a new instance of an object every time I need to use something from that class. Is there any way I can call a class within a class and return it as an object for all the methods within the class? I've tried the methods below, but no luck I've tried others, but I'm trying to keep it brief and get what I'm trying to do across. <?php class QueryFactory extends MySQLi { public $err = new error(); //Doesn't work. public $err = error(); //Nope. #This is the function that I need the $err object for. function set($fields, $newvals) { if ( is_array($fields) && is_array($newvals) ) { if ( count($fields) != count($newvals) ) { //Instead of below, I want to do something like $err->('Array lengths must match for method', 256, $islogged = 1); trigger_error('Array lengths must match for method', 256); } } } } The thing is, I have a "run.inc.php" which does include and create new objects for running just the basic app and if I try to redeclare the error class in query.class.php, it gives me an error saying I can't do that, but if i try to call $err from the page that has all the classes defined it throws an error saying that my method is undeclared. I'd like my error class be available to every other class I create so I can display and log errors as needed. Any suggestions or links to point me where I'd like to go? I've got a monumental problem on my hands... 😂 The website that I've been working on - for years - for my startup business is just about done, but because I have taken so long to code things, my HTML is very outdated, and is *not* mobile friendly. I was hoping to go live with my website in the next month or two, but considering that over half of Internet users are on mobile, it makes me wonder if I should release my rigid, un-responsive website as-is, or take months trying to re-tool things. That, in itself, will be a monumental task, BUT it also makes me wonder if I will break all of my tens of thousands of lines of PHP and MySQL? A very loaded question, for sure, but if you were me, what would you do? What I am really fearful of is FUBAR'ing my PHP code which I have spent thousands of hours testing and am hesitant to even blink at?! Edited January 3 by SaranacLakeHi,
Can you please tell me in witch conditions should be used base tag.
If have a website that base tag it's define in header like: <base href="http://www.website.com/">
What's the meaning of this ?
Thank you
Hello, I am attempting to get the base URL of the directory that the CMS was installed, not the main directory. Here's what I mean: For example, let's say my domain is http://www.example.com but I install my CMS under http://www.example.com/test/cms and on another occasion I install it under http://www.example.com/cms, and on another occasion http://www.example.com/my/new/cms/ I would like my base url for the http://www.example.com/cms installation, to be "http://www.example.com/cms" and my base url for the http://www.example.com/test/cms installation to be "http://www.example.com/test/cms" and so on, without me having to manually change anything. How do I go about obtaining the directory that corresponds to that particular installation? I know it is possible because Joomla does it automatically. I have already tried numerous combinations using $_SERVER['HTTP_HOST'], $_SERVER['REQUEST_URI'], $_SERVER['SCRIPT_NAME'], and so on, no luck. Hi Hopefully someone can help me. My knowledge of PHP doesnt go any further than looking at identifying areas of code and copy and paste - as basic as you get! Basically i have a php script installed that produces an RSS feed for me to use with google base. There is a little problem were it does not pull the sale price(known as special) into googlebase and it will instead show the original price. I have identified what needs to be changed but i dont know the correct syntax. I somehow need to get something similar to the following IF ELSE into the code below (this is taken from the same php script that shows the special price on the actual rss feed) foreach ($product_data as $result) { $special = $model_catalog_product->getProductSpecial($result['product_id']); if ($special) { $price = $special; } else { $price = $result['price']; } if ($useTax) { $price = $currency->format($tax->calculate($price, $result['tax_class_id'], $config->get('config_tax')), $currency->getCode()); } else { $price = $currency->format($price, $currency->getCode()); } The code below is were i need the If Else inserted. <?php foreach ($products as $product) { ?> <item> <title><?php echo htmlspecialchars($product['name'], ENT_QUOTES, 'utf-8'); ?></title> <g:brand><?php echo htmlspecialchars($product['brand'], ENT_QUOTES, 'utf-8'); ?></g:brand> <g:condition>new</g:condition> <g:product_type><?php echo $taxonomy; ?></g:product_type> <description><?php echo htmlspecialchars($product['desc'], ENT_QUOTES, 'utf-8'); ?></description> <link><?php echo str_replace('&', '&', $product['href']); ?></link> <pubDate><?php echo $product['add_date']; ?></pubDate> <!--guid isPermaLink="true"><?php echo $product['href']; ?></guid--> <g:id><?php echo (int)$product['id']; ?></g:id> <!--g:upc><?php echo sprintf("%012s", $product['id']); ?></g:upc--> <g:image_link><?php echo $product['thumb']; ?></g:image_link> <!--g:expiration_date>2010-01-01</g:expiration_date--> <g:price><?php echo $product['price']; ?></g:price> <g:mpn><?php echo htmlspecialchars($product['model'], ENT_QUOTES, 'utf-8'); ?></g:mpn> <g:weight><?php echo $product['weight']; ?></g:weight> <g:currency><?php echo $config->get('config_currency'); ?></g:currency> </item> <?php } ?> The <g:price> is what googlebase reads to get the price of the product. The problem seems to be that there is no if else statement here to output the special price if there is one. Any help would be greatly appreciated, i tired emailing the developer but i have been ignored and as you can see i'm pretty clueless I'm trying to figure out how to add "\fs13" to the base64 encoding. For example, the "ad->text" field would look like this
<ad-content type="rtf">ZGZnIGRmZyBkZmcgZGZnIGRmZyBkZmcgZGZnIGRmZyBkZmcgZGZnIGRmZyBkZmcgZGZnIGQ=</ad-content>
The code to generate the above is -- <ad-content type=\"rtf\">".htmlentities(base64_encode($ad->text))."</ad-content>";
I need the encoding to include the "\fs13" in front of the encoded ad-content. The "\fs13" is simply a font size that will tell the system what font size to use.
<ad-content type="rtf">ZGZnIGRmZyBkZmcgZGZnIGRmZyBkZmcgZGZnIGRmZyBkZmcgZGZnIGRmZyBkZmcgZGZnIGQ=</ad-content>
I'm also trying to encode an additional field within the "ad-content type". The present code looks like this:
<ad-content type=\"rtf\">".htmlentities(base64_encode($ad->text))."</ad-content>";
I need to add "($ad->photo_file_name)" to the above, so that the "ad->text" and the "ad->photo_file_name" are within the ad-content type that is being decoded. Hope that makes sense, appreciate ant help, Thanks! My goal was to create a constant that could be included on the pages, that no matter where it was located in the structure, would be able to find the template files, css, images, etc. using the following code: Code: [Select] if($_SERVER['HTTP_HOST'] == "localhost"){ define('SITEURL', 'http://' . $_SERVER['HTTP_HOST']); define('SITEPATH', $_SERVER['DOCUMENT_ROOT']); define('CSS', $_SERVER['DOCUMENT_ROOT'] . '/css/'); define('IMAGES', $_SERVER['DOCUMENT_ROOT'] . '/images/'); } else{ define('SITEURL', 'http://' . $_SERVER['HTTP_HOST']); define('SITEPATH', $_SERVER['DOCUMENT_ROOT']); define('TEMPLATE', $_SERVER['DOCUMENT_ROOT'] . '/incs/template/'); define('CSS', $_SERVER['DOCUMENT_ROOT'] . '/css/'); define('IMAGES', $_SERVER['DOCUMENT_ROOT'] . '/images/'); } I put the above in a variables.php file that is in the includes folder (named incs) and I call it using the typical include statement. The problem is that when I use the constant to grab the CSS file, its not working when using: Code: [Select] <link rel="stylesheet" href="<?php echo CSS . "template.css" ?>" type="text/css" media="screen" /> I can view the page source and it has the path right, but I cannot figure out how to get it to actually pull in the css file. I know the echo command is not correct, at least I dont think it is, but have not been able to figure out any other way. Also, is there a better way to define the constants to the file locations and have it automatically detect whether its on the test server or production and then be able to reference those locations no matter where it is in the structure? Hello First of all thanks for your help in advance. I build a members website and can use HTML but seem to be going round in circles with php. So Ive made a page that allows users to input there details and register this DOES Work and adds the data to a mysql data base. However I would like when they click register it sends them a email to confirm there info and at the same time send myself one so I can check there details. this is the link http://www.asian-travel-club.co.uk/php/files/register.htm Once this is done I would like to be able to see on a admin page that has a username and password to allow me to active and deactive there members. I know this would need a button added this is where I get lost. the link to the admin page ive made is http://www.asian-travel-club.co.uk/php/files/admin/ Then once i actived them they will recive an auto activtion email . I dont seem to be able to see data from the Database on mysql but i can interact with it. As one you register if you try to log in it say that the username and passwodr is incorrect. I TAKE IT IS BECAUSE THE USER DOES NOT HAVE PERMISSION> how do i do this? Any way if you go to forot password page it allows you to enter data and on submittion it chz the database and then sends you an email with your username and password attached. This is the link to the password recover page. http://www.asian-travel-club.co.uk/php/files/password_recover.php this is what is in my config.php <?php define('DB_SERVER', ''); // database server/host define('DB_USER', ''); // database username define('DB_PASS', ''); // database password define('DB_NAME', ''); // database name ?> Please help if you can i have php code, <?php include ("connect.php"); $selecteddate = $_POST['sdate']; $sql1 = "select date from game1"; $query1 = mysql_query($sql1) or die(mysql_error()); while($row = mysql_fetch_assoc($query1)) { $rowdate = $row['date']; // problem here i this while loop only compare my latest last value in database. i want a code here which search all the data in "date" field. } if($selecteddate == $rowdate) { echo "Date already Exists"; } else { // form insertion data code here which i have and working fine } SHINSTAR is online now Add to SHINSTAR's Reputation Report Post Edit/Delete Message i have just sent the last 4 hours trying to connect to the msql database here is the to sets of code i i'm using <?php $db_host = "host"; $db_usernamen = "username"; $db_pass = "password" $db_name = "database name"; mysql_connect("$db_host","$db_username","$db_pass") or die ("couldnot connect to mysql"); mysql_select_db("db_name") or die ("no database"); ?> this code i'm using to connect to the database <?php require "connect_to_mysql.php"; echo "<h1>success in database connection! happy coding</h1>"; ?> and i have used this one as a quick test. i have up loaded the the two codes to the sever however when i opened the web site to test it all i get is a blank screen. i have looked at a number of codes like this one and i can't see anything wrong with the code. i have uploaded the codes three times just in case the files had been corrupt while uploading have every this has not work if anyone can help i would be very greatful Hi everyone, Here's the part of the script I think is wrong : <?php include "util/log.php"; include "util/connect.php"; if (loggedin() == $NO) { header("Location: login.php"); exit(); } else if (isset($_GET["p"])) { $udata = explode("-", $_COOKIE["log"]); $query = "SELECT * FROM l_users WHERE user='$udata[0]'"; $usrsql = mysql_query($query) or handledberror(mysql_error()); $usrdata = mysql_fetch_array($usrsql); switch ($_GET["p"]) { case "delete": include "util/linkfunc.php"; if (isset($_GET['id'])) delete_link($_GET['id']); else delete_all(); $CONTENT = "pages/urls.php"; break; case "approve": include "util/approve.php"; $CONTENT = "pages/approve.php"; break; case "urlview": case "add": case "edit": include "pages/modify.php"; $CONTENT = "pages/edit.php"; break; case "reset": include "util/linkfunc.php"; if (isset($_GET['id'])) reset_link($_GET['id']); else reset_all(); $CONTENT = "pages/urls.php"; break; case "urls": default: $CONTENT = "pages/urls.php"; } } else { $udata = explode("-", $_COOKIE["log"]); $query = "SELECT * FROM l_users WHERE user='$udata[0]'"; $usrsql = mysql_query($query) or handledberror(mysql_error()); $usrdata = mysql_fetch_array($usrsql); $CONTENT = "pages/urls.php"; } ?> <html> <head><title>EzyLinkExpire :: Member's Area</title><head> <body bgcolor="#1D2B60" link=#CCFFFF vlink=#CCFFFF> <table align="center" cellspacing="0" width=90% bgcolor="white" bordercolordark="black" bordercolorlight="black"> <tr> <td bgcolor="#1D2B60"> <img src="images/logo.gif" border="0"></td> <td valign=top bgcolor="#1D2B60" align=right><font color="white" size="1" face="Verdana">Welcome <? print $usrdata["fname"] . " ". $usrdata["lname"]; ?>!<br>User Since: <? print date("F d Y",$usrdata["since"]); ?><br>Server Time:<? print date("r"); ?><br><a href="login.php?a=logout" color=#CCFFFF>Click Here To Logout</a><br><a href="members.php" color=#CCFFFF>Click Here To Goto the Main Page</a></font></td> </tr> <tr><td colspan=2 height=14 bgcolor="#1D2B60"></td></tr> <tr> <td width="100%" height="100%" colspan=2 bgcolor="white" bordercolordark="black" align="center" bordercolorlight="black" border=1 valign="top"> <br><? include $CONTENT; ?><br><br> </td> </tr> </table> </body> <style type="text/css"> table.t {border: thin solid #000000; background-color: #FFFFFF} td.th {border: thin solid #000000; background-color:#FFFFFF; font-style: bold 12px; text-align:center; font-size: 12px; font-weight:bold} td.t {border: thin solid #000000; background-color:#FFFFFF; font-style: bold 12px; text-align:center; font-size: 12px; font-weight:bold} td.te {border: thin solid #000000; background-color:#FFFFFF; text-align:center; } td.ac1 {border: thin solid #000000; background-color:#FFFFFF; text-align:left; } td.ac2 {border: thin solid #000000; background-color:#FFFFFF; text-align:left; } a.t {color: #3366FF} a.msg {color: #3366FF} font.msg {font-style: bold 12px; font-size: 12px; font-weight:bold} </style> <script language='javascript'> function deleteconfirm() { if (confirm("Are you sure you want to delete all links?")) document.location = "members.php?p=delete"; } function resetconfirm() { if (confirm("Are you sure you want to reset the hit count for all links?")) document.location = "members.php?p=reset"; } </script> </html> Thank you, Sylvain in my php PDO system im have to use finger print reader for user input. i cannot find any codes related to that. im using suprema finger print reader. please suggest me solutions. thanks ok let say i pull a video from youtube if i post the info into the textarea and pass it into SQL the data/text has then been change some words have been change or deleted i know that it's happening before it makes it into the SQL and i know there is a way to make it work just dont know how i know there is a way bc if u was to edit your SQL base using phpmyadmin it works fine they use a textarea and a few other things but cant tell just what they are doing to make it work praying someone know a fast way to make it work would think it would be like a onSubmit change all html codes (< > any other) into some other code then change back later before they get put into SQL but not sure how to do this im not the best with php if u dont mind can you give me more info ? lol if not then meh i will work with whatever i can get lol looked all over the net for this with no luck ty you for your time |