Search the Community
Showing results for tags 'class'.
-
I had such a class : class NodeElement { no; x; y; tre; tdno; tdx; tdy; cbox; nodesArray; nodesTable; selected; constructor( x, y,nodesArray, nodesTable) { nodeCounter++; this.no = nodeCounter; this.x = x; this.y = y; this.nodesArray = nodesArray; this.nodesTable = nodesTable; //create elements this.tre = document.createElement("tr"); this.tre.id = "row"+this.no; this.tdno = document.createElement("td"); this.tdno.id = this.no; this.tdno.innerHTML = this.no; this.cbox = document.createElement("input"); this.cbox.type="checkbox"; this.cbox.id="cbox"+this.no; this.cbox.value=this.no; this.cbox.name="cbox"+this.no; this.cbox.setAttribute('onclick','select(this)'); this.tdx = document.createElement("td"); this.tdx.id="tdx"+this.no; this.tdx.innerHTML = this.x; this.tdy = document.createElement("td"); this.tdx.id="tdy"+this.no; this.tdy.innerHTML = this.y; } } I want to pass complete class object(i.e instantiated one) to a function select() as parameter when I click(i.e. checked the checkbox object of the class instance). My question is that line : this.cbox.setAttribute('onclick','select(this)'); I tried that too : this.cbox.setAttribute('onclick','select("'+this+'")'); but not worked. I could no achieve to pass neither checkbox nor the class object(NodeElement) to function select() as parameter. How can I do that?
-
Good evening, Phreaks. Quick question. I have this method here -> public function get($table, $where = [], $column = "*") { return $this->action("SELECT {$column}", $table, $where); } It works great as long as the call to it includes the $where array. I want both $where and $column to be optional here and $where to be an array when it's included. if I only use the $table parameter (which is the only one I want to be required). I keep getting a Could one of you fine folks please explain to me about this error and why I need the $where parameter when I want it to be optional. Thank you
-
Hi Freaks, I've been trying to put together subscribe functionality on a project. Been at it for hours and can't make any progress. The categories that a user is subbed to are stored in comma separated string in the database and pulled out into $_SESSION['user_subs'] I have these 2 methods here to start -> <?php private function userSubscribed($cat_id) { $category = $this->getCategoryByID($cat_id); if(in_array($category, $_SESSION['user_subs'])) { echo "user subscribed"; return true; } else { echo "user NOT subscribed"; return false; } } public function displaySubscribedButton($cat_id) { $subscribed = $this->userSubscribed($cat_id); if($subscribed) { $action_btn = "<td><a href='category_posts.php?cat_id=$cat_id' name='sub_btn' class='btn btn-secondary'>Unsubscribe</a>"; } else { $action_btn = "<td><a href='category_posts.php?cat_id=$cat_id' name='sub_btn' class='btn btn-danger text-color- primary'>Subscribe</a>"; } return $action_btn; } They've both been well tested and I know they're working correctly. Then I have this one (which is the problem child) -> <?php public function updateSubscriptionCategory($cat_id, $username) { $category = $this->getCategoryByID($cat_id); $subscribed = $this->userSubscribed($cat_id); print_r($_SESSION['user_subs']); if($subscribed){ unset($_SESSION['user_subs'][$category]); $subs = $_SESSION['user_subs']; $subscribed = false; } else { $new_sub = ",".$category; $subs = array_push($_SESSION['user_subs'], $new_sub); $subscribed = true; } $stmt = $this->conn->prepare("UPDATE ".User::$table." SET subs=? WHERE username=?"); if($stmt) { $stmt->execute([$subs, $username]); } else { echo "you fucked up"; } } I call it from the category file, here -> <?php require_once("assets/initializations.php"); $post_obj = new Post($conn, $username); $cat_obj = new Category($conn, $username); $cat_id = $_GET['cat_id']; if(isset($_POST['sub_btn'])) { $cat_obj->updateSubscriptionCategory($cat_id, $username); // header("Location: category_posts.php?cat_id=$cat_id&cat_title=$cat_title"); } but the page only reloads no changes are made not on the page nor in the db nor do I get any feedback, not from the 'print_r' or the else at the bottom. I feel like it's not even running this method. Was hoping that someone sees something that I've been missing. 8 hours in and I'm still not able to get it to work. TIA for all input
-
Hi guys, I am trying to calculate hours a person works by calculating the values of text fields in a form. However, when I load the page I get "Class 'times_counter' not found. Here is the calculation code" if(isset($_POST['calculate']) != ""){ class times_counter { private $hou = 0; private $min = 0; private $sec = 0; private $totaltime = '00:00:00'; public function __construct($times){ if(is_array($times)){ $length = sizeof($times); for($x=0; $x <= $length; $x++){ $split = explode(":", @$times[$x]); $this->hou += @$split[0]; $this->min += @$split[1]; $this->sec += @$split[2]; } $seconds = $this->sec % 60; $minutes = $this->sec / 60; $minutes = (integer)$minutes; $minutes += $this->min; $hours = $minutes / 60; $minutes = $minutes % 60; $hours = (integer)$hours; $hours += $this->hou % 24; $this->totaltime = $hours.":".$minutes; } } public function get_total_time(){ return $this->totaltime; } } $times = array( $mondiff->format('%H:%I'), $tudiff->format('%H:%I'), $weddiff->format('%H:%I'), $thdiff->format('%H:%I'), $fridiff->format('%H:%I'), $satdiff->format('%H:%I'), $sundiff->format('%H:%I'), ); $counter = new times_counter($times); I had this on an old project, which I no longer have but it worked then. Any ideas?
-
I've got a bit of jQuery that is getting the bit of data that I want to search the page for. This is posted below. $(".pagelink").click(function(){ var myClass = this.className; var number = myClass.substr(myClass.length - 1); }); This bit is working ok. It gets the last bit of the element's class name which is a number incremented by the PHP that echoes it out. Now I want to search the page for a div that has a class that contains that var number. There will be a div somewhere on the page with a class that contains that number. It will be called either row0, row1, row2, row3 etc etc. The div is not a descendant element of the pagelink class, it is somewhere else so I don't think the find() variable is suitable. Any help will be greatly appreciated, thanks!
-
I have two questions relating to each other which are regarding - both function __autoload and adding products to a class? Code for an autoload function (please see code #1), the output prints - but also gives an error message? Moreover, I also receive the notification in my php editor "class 'ooo' not found"? If I may ask a silly question I have noticed some autoload fucctions have implode and explode - how would I write one of these? The output and error: My Antonia: Willa Cather (5.99) Fatal error: Class 'ooo' not found in C:\ Code#1: <?php // we've writen this code where we need function __autoload($classname) { $filename = "./". $classname .".php"; include_once($filename); } // we've called a class *** $obj = new ooo(); ?> ------------------------------------------------------------------------------------------------------------------------------ How would I add more products to this product class? code#2: <?php class shopProduct { public $title; protected $producer = []; public $price; public function __construct($title, $producerName1, $producerName2, $price) { $this->title = $title; $this->producer[] = $producerName1; $this->producer[] = $producerName2; $this->price = $price; } public function getProducer() { return implode(' ', $this->producer); } } class ShopProductWriter { public function write ($shopProduct) { $str = "{$shopProduct ->title}: " . $shopProduct -> getProducer() . " ({$shopProduct -> price})\n"; print $str; } } $product1 = new ShopProduct("My Antonia", "Willa", "Cather", 5.99); $writer = new ShopProductWriter(); $writer -> write($product1); ?>
-
I have to write small segment of PHP code to print the word(s) 'Hello, World!' in uppercase letters, I have thus far wrote a small section of code that prints the output 'Hello, World!'. But, I'm completely stuck on how to make the letters all uppercase?!?? Moreover; that strtoupper goes somewhere in there right? <?php class TextFunctions { public static $string = 'Hello, World!'; static public function strtoupper() { } } echo TextFunctions::$string; ?>
-
I have been using the below method to access my database for some time now and just wanted to make sure im doing the correct thing. My application runs perfectly but im just trying to improve my programming skills. The classes are all loaded in with an autoloader so in theory using the classes below I could just call: echo User::getUsername(1); Like I say it works fine I would just love some feedback about what other people do and suggestions on something that might run better or looks cleaner. class Db { private static $db_read; private static $db_write; public static method read(){ if( self::$db_read == null ){ //create new database connection is it doesnt exist self::$db_read = new PDO(); } return self::$db_read; } public static method write() { if( self::$db_write == null ){ //create new database connection is it doesnt exist self::$db_write = new PDO(); } return self::$db_write; } class User { public static function getUsername($user_id){ $d = Db::read()->prepare('select * from user where id = ? '); $d->execute( array($user_id) ); $user = $d->fetch(); return $user['username']; } }
-
Please see attached my bank account class files. The key guidance I need is how to instantiate a class from another class. For example, you can see in Customer.class.php, I instantiate a new Account, but am not sure how i pass in the balance and account number to Customer in order that they can instantiate the Account? This is the same as Account instantiate a BankCard object. I am a little confused - any help appreciated. BankAccountApp.zip
-
This code works without problems: <?php namespace NamespaceA; class A extends \NamespaceB\B {} namespace NamespaceB; class B {} But why the following code cause Fatal error: Class 'NamespaceB\B' not found in ...file? <?php namespace NamespaceA; class A extends \NamespaceB\B {} namespace NamespaceB; class B extends \NamespaceC\C {} namespace NamespaceC; class C {} And this code also works without problems: <?php namespace NamespaceA; class A extends \NamespaceB\B {} namespace NamespaceC; class C {} namespace NamespaceB; class B extends \NamespaceC\C {} Without any namespace, also Fatal error: Class 'B' not found in ...file: <?php class A extends B {} class B extends C {} class C {} Works without problems: <?php class A extends B {} class B {} And yes everything is in the same PHP file....
-
Hello, I'm starting using class and have a question for you guys : Let's consider a class "customer". I want to code a search tool. Where should I put my search function ? Within the customer class ? In another "search" class ? Other solution ? Thanks for help !
-
All my code is returning is the username... Please help. index.php <?php include('user.class'); $user = new user("Jbonnett", "0", "Admin", "Jamie", "Bonnett", "jbonnett@site.co.uk", "01/09/1992"); echo "username: " . $user->getUsername() . "<br/>"; echo "id: " . $user->getId() . "<br/>"; echo "level: " . $user->getLevel() . "<br/>"; echo "Forename: " . $user->getForename() . "<br/>"; echo "Surname: " . $user->getSurname() . "<br/>"; echo "Email: " . $user->getEmail() . "<br/>"; echo "Dob: " . $user->getDob() . "<br/>"; ?> user.class <?php class user { private $username; private $id; private $level; private $forename; private $surname; private $email; private $dob; public function user($username, $id, $level, $forname, $surname, $email, $dob) { $this->setUsername($username); $this->setId($id); $this->setLevel($level); $this->setForename($forename); $this->setSurname($surname); $this->setEmail($email); $this->setDob($dob); } public function destroy() { unset($this->username); unset($this->id); unset($this->level); unset($this->forename); unset($this->surname); unset($this->uemail); unset($this->dob); } public function setUsername($username) { $this->username = $username; } public function getUsername() { return $this->username; } public function setId($id) { $this->id = $id; } public function getId() { return $this->$id; } public function setLevel($level) { $this->level = $level; } public function getLevel() { return $this->level; } public function setForename($forename) { $this->foreName = $forename; } public function getForename() { return $this->forename; } public function setSurname($surname) { $this->surName = $surname; } public function getSurname() { return $this->surname; } public function setEmail($email) { $this->email = $email; } public function getEmail() { return $this->email; } public function setDob($dob) { $this->dob = $dob; } public function getDob() { return $this->dob; } }; ?>
-
I want to create a singleton class that read multidimensional array from txt file and flatten the array retrieved. This is what I have tried so far: class singleton { protected static $instance = null; public static function getInstance() { if (!isset(static::$instance)) { static::$instance = new static; } return static::$instance; } public static function flattenArray($array) { $return = array(); $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array)); foreach ($iterator as $value) { $return[] = $value; } return $return; } public static function loadFile($path) { $file_handle = fopen($path, "r"); while (!feof($file_handle)) { $line = fgets($file_handle); $rawarray[] = $line; } $flattedarray = self::flattenArray($rawarray); fclose($file_handle); return $flattedarray; } With the txt file containing: array('a', 'b', array(array('c'), 'd'), 'e', array('f'), 'g') I run the class with: include 'singleton.php'; $singleton = singleton::getInstance(); $flattedarray = $singleton->loadFile("file.txt"); echo '<pre>'; print_r($flattedarray); echo'</pre>'; I get as a result: Array ( [0] => array('a', 'b', array(array('c'), 'd'), 'e', array('f'), 'g') ) Which is the same array found in the txt file. how can i do it without using eval. What am I doing wrong ?
-
I am trying to put an rss feed from my Flickr account into my website I have got thus far with my class:- <?php // Flickr Class class flickr { // Properties var $feed; //=================== // Construct Flickr function __construct($feed) { $this->feed = $feed; } //=================== // Parse Method function parse() { $rss = simplexml_load_file($this->feed); $photodisp = array(); foreach ($rss->channel->item as $item) { $link = (string) $item->link; // Link to this photo $title = (string) $item->title; // Title of this photo $media = $item->children('http://search.yahoo.com/mrss/'); $thumb = $media->thumbnail->attributes(); $url = (string) $thumb['url']; // URL of the thumbnail $width = (string) $thumb['width']; // Width of the thumbnail $height = (string) $thumb['height']; // Height of the thumbnail $photodisp[] = <<<________________EOD {$title} ________________EOD; } return $photodisp; } //=================== // Display Method function display($numrows=6,$head="Photos on Flickr") { $photodisp = $this->parse(); $i = 0; $thumbs = <<<____________EOD $head ____________EOD; while ( $i < $numrows ) { $thumbs .= $photodisp[$i]; $i++; } $trim = str_replace('http://api.flickr.com/services/feeds/photos_public.gne?id=', '',$this->feed); $user = str_replace('〈=en-us&format=rss_200','',$trim); $thumbs .= <<<____________EOD View All Photos on Flickr ____________EOD; return $thumbs; } //=================== } //End of Class ?> // <- Line 66 and it gives me "Parse error: syntax error, unexpected end of file in C:\wamp\www\image-a-nation\test4_class.php on line 66". I thought it might be an unclosed brace/bracket or something like that, but no amount of checking finds anything - would appreciate a fresh pair of eyes...
-
My error happens on line #81 My error: Parse error: syntax error, unexpected 'class' (T_CLASS), expecting function (T_FUNCTION) in w06c02cxx.php on line 81 Troubleshooting notes: I've been reviewing this exercise throughout the weekend trying to find my error. I've used my code editors syntax highlighting tools (BBedit 10), but still the error persists. I learned about the 20/20/20 rule during this process and have practiced that while attempting to debug the code. I've scoured the web trying to find examples to help me, but i'm a new and nothing i've thus found has helped me to resolve my error, hoping someone here can help. I think the error is happening in my survey class, somewhere before line #81 Link to error: http://zephir.seattlecentral.edu/~jstein11/itc250/z14/surveys/w06c02cxx.php require '../inc_0700/config_inc.php'; #provides configuration, pathing, error handling, db credentials $config->titleTag = smartTitle(); #Fills <title> tag. If left empty will fallback to $config->titleTag in config_inc.php $config->metaDescription = smartTitle() . ' - ' . $config->metaDescription; //END CONFIG AREA ---------------------------------------------------------- get_header(); #defaults to header_inc.php $mySurvey = new Survey(1);//all our code happens in here if ($mySurvey->isValid){ echo ' The title of the surevis is ' . $mySurvey->Title . ' <br />'; echo ' The title of the surevis is ' . $mySurvey->Description . ' <br />'; }else{echo ' No such survey exists';} dumpDie($mySurvey); //like var_dump inside/available this app because of common file get_footer(); #defaults to footer_inc.php class Survey{//class creates one object at a time, creates as many as you want //create properties public $SurveyID = 0; public $Title = ''; public $Description = ''; public $isValid = FALSE; public $Questions = array();// how we add an array of questions to a survey function __construct($id){ $id = (int)$id; //cast to an integer - stops most sequal injection in this case if($id == 0){ return false; //don't bother asking database, there is no frog, don't ask - no data no dice } $sql = "select Title, Description, SurveyID from sp14_surveys where SurveyID = $id"; $result = mysqli_query(IDB::conn(),$sql) or die(trigger_error(mysqli_error(IDB::conn()), E_USER_ERROR)); //echo '<div align="center"><h4>SQL STATEMENT: <font color="red">' . $sql . '</font></h4></div>'; if(mysqli_num_rows($result) > 0) {#there are records - present data while($row = mysqli_fetch_assoc($result)) {# pull data from associative array $this->SurveyID = (INT)$row['SurveyID']; $this->Title = $row['Title']; $this->Description = $row['Description']; } $this->isValid = TRUE; } @mysqli_free_result($result);//at symbol surpresses multiple copies of an error silences a line basically $sql = "select * from sp14_questions where Survey14 = $id"; $result = mysqli_query(IDB::conn(),$sql) or die(trigger_error(mysqli_error(IDB::conn()), E_USER_ERROR)); if(mysqli_num_rows($result) > 0) {#there are records - present data while($row = mysqli_fetch_assoc($result)) {# pull data from associative array $this->Questions[] = new Question((INT)$row['QuestionID'],$row['Question'],$row['Description']); } }//end of constructor }//end of survey class //BEGIN new question object class Question{ public $QuestionID = 0; public $Text = ''; public $Description = ''; function __construct($QuestionID, $Question, $Description){ $this->QuestionID = $QuestionID; $this->Question = $Question;// field is named Question $this->Description = $Description;// the context info about the question asked }//END question Constructor }// END question Class } w06c02cxx.php
-
So I have this CMS that I have spent the last 5 years building and rebuilding and updating blah blah. It's a fairly extensive piece work and I am now looking at converting the entire system over to OOP. I am fairly new to OOP but understand the easy basics of it. I do fight with the concept of when to make a class and when to just make a normal function. I have many functions that I built specific to how my system works and some I suppose could be grouped into categories but then many others are just plain functions that only serve one purpose and may only be a few lines long. I will be using the spl_autoload_register() to load the classes as needed which is obviously much easier than including all the function pages that are needed. So for that reason I like the idea of making classes for everything but it just seems like more than is needed. So what I am looking for is some insight as to when and how to decide if a class should be made and whether to group functions by category to limit the amount of classes OR to just leave them as normal functions. Here is a example function for creating a thumbnail. I would guess that I could make a class called Thumb and put this in it, but what exactly would be the benefit of that based on the syntax of the function AND could you show me how you would convert this to OOP to make it worth while putting it in a class? // Creates a thumbnail function createThumb($img, $type, $dest = NULL, $xy = NULL) { if($type=="admin_product") { $thumb_width = $GLOBALS['admin_thumb_width']; $thumb_height = $GLOBALS['admin_thumb_height']; } elseif($type=="custom") { $thumb_width = ($dest !== NULL) ? $xy['x'] : (int)$_GET['width']; $thumb_height = ($dest !== NULL) ? $xy['y'] : (int)$_GET['height']; } $src_size = getimagesize($img); if($src_size['mime'] === 'image/jpg') {$src = imagecreatefromjpeg($img);} elseif($src_size['mime'] === 'image/jpeg') {$src = imagecreatefromjpeg($img);} elseif($src_size['mime'] === 'image/pjpeg') {$src = imagecreatefromjpeg($img);} elseif($src_size['mime'] === 'image/png') {$src = imagecreatefrompng($img);} elseif($src_size['mime'] === 'image/gif') {$src = imagecreatefromgif($img);} $src_aspect = round(($src_size[0] / $src_size[1]), 1); $thumb_aspect = round(($thumb_width / $thumb_height), 1); if($src_aspect < $thumb_aspect)//Higher { $new_size = array($thumb_width, ($thumb_width / $src_size[0]) * $src_size[1]); $src_pos = array(0, (($new_size[1] - $thumb_height) * ($src_size[1] / $new_size[1])) / 2); } elseif($src_aspect > $thumb_aspect)//Wider { $new_size = array(($thumb_height / $src_size[1]) * $src_size[0], $thumb_height); $src_pos = array((($new_size[0] - $thumb_width) * ($src_size[0] / $new_size[0])) / 2, 0); } else//Same Shape { $new_size = array($thumb_width, $thumb_height); $src_pos = array(0, 0); } if($new_size[0] < 1){$new_size[0] = 1;} if($new_size[1] < 1){$new_size[1] = 1;} $thumb = imagecreatetruecolor($new_size[0], $new_size[1]); imagealphablending($thumb, false); imagesavealpha($thumb, true); imagecopyresampled($thumb, $src, 0, 0, 0, 0, $new_size[0], $new_size[1], $src_size[0], $src_size[1]); //$src_pos[0], $src_pos[1] 3rd and 4th of zeros position on above line if($src_size['mime'] === 'image/jpg') { if($dest !== NULL) { imagejpeg($thumb, $dest, 95); } else { header('Content-Type: image/jpeg'); imagejpeg($thumb, NULL, 95); } } elseif($src_size['mime'] === 'image/jpeg') { if($dest !== NULL) { imagejpeg($thumb, $dest, 95); } else { header('Content-Type: image/jpeg'); imagejpeg($thumb, NULL, 95); } } elseif($src_size['mime'] === 'image/pjpeg') { if($dest !== NULL) { imagejpeg($thumb, $dest, 95); } else { header('Content-Type: image/jpeg'); imagejpeg($thumb, NULL, 95); } } elseif($src_size['mime'] === 'image/png') { if($dest !== NULL) { imagepng($thumb, $dest); } else { header('Content-Type: image/png'); imagepng($thumb); } } elseif($src_size['mime'] === 'image/gif') { if($dest !== NULL) { imagegif($thumb, $dest); } else { header('Content-Type: image/gif'); imagegif($thumb); } } imagedestroy($src); } Your insight is appreciated.
-
HitCounter.php CountVisits2.php I'm struggling with this assignment, I'm not sure what I'm doing wrong! If somebody could please point out what my errors are that would be great. I attached the two files I'm using above; below are the directions for the assignment: this is the error I get "[03-Apr-2014 21:10:56 America/Denver] PHP Fatal error: Call to undefined function my_sql_fetch_row() in /project5/HitCounter.php on line 78" "For this project, you will create a HitCounter class that counts the number of hits to a Web page and stores the results in a MySQL database. Use a private data member to store the number of hits and include public set and get member functions to access the private counter member variable. Note, you must develop 2 php files for this project. The first is a class called HitCounter.php and the second is a file called CountVisits.php. The CountVisits file will be the one used by the user and it will instantiate an instance of the HitCounter class. The HitCounter class takes care of opening the database file and table and obtaining the current number of hits, placing that number in a private variable. That private variable is accessible in the object by calling the "get" function. Before terminating, the CountVisits program has to set the new value using the "set" function (in the class definition, the "set" function should increment the current counter by one and update the database). Note that part of the constructor function in HitCounter.php should be to check to see if your table exists and then create it, if it does not, and initialize the table with values."
-
does anyone know a class that can generate a menu with category and subcategory that connects to mysql with pdo ? thank you
-
so i found a pdo class to connect to mysql with pdo and looks easy to customize however i have an error that i can't figure it out class <?php class ApplicationResourcePool { static var $_dbHandle; // line 5 private static $_dbConfig = array( 'dsn' => 'mysql:dbname=vax', 'username' => 'vax', 'password' => 'veryrandpasswd', ); public static getDbHandle(){ if(self::$_dbHandle == null){ self::$_dbHandle = new PDO( self::$_dbConfig['dsn'] , self::$_dbConfig['username'], self::$_dbConfig['password'] ); } return self::$_dbHandle; } } class StockMapper { protected $_dbh; public __construct($dbh = null) { if($dbh == null){ $this->_dbh = ApplicationResourcePool::getDbHandle(); } else { $this->_dbh = $dbh; } } public getStockById($stockId){ $sth=$this->_dbh->prepare("SELECT * from stock WHERE id = :stockId"); $sth->bindParam(":stockId", $stockId); $sth->execute(); $result = $sth->fetch(PDO::FETCH_ASSOC); return $result[0]; } } $stockMapper = new StockMapper(); $stockData = $stockMapper->getStockById('302'); ?> Parse error: syntax error, unexpected 'var' (T_VAR), expecting variable (T_VARIABLE) in /path/index.php on line 5 i really don't know what to do
-
I know how to dynamically create class properties like this: class Sample { /* Creates instances of classes and dynamically assigns them to properties * Example: If "test.php" is in the Classes folder, an instance of its class ... * ... will be assigned to $this->test. */ public function createInstances() { foreach(glob("Classes/*.php") as $file) { require_once $file; $fileName = basename($file, ".php"); if(class_exists($fileName)) { $lclass = strtolower($fileName); $this->{$lclass} = new $fileName(); } } } } $obj = new Sample(); $obj->createInstances(); And I'm using this in my project. But there's something I want to make using the same sort of principle - I want to dynamically create properties from all of the arguments passed to the constructor. The thing is that I don't know how many arguments will be passed. I think you can use `for` loops for this kind of thing, but I'm not sure how I would go about doing that.
-
I want to require_once all of the files in my directory and assign instances of their classes to properties in the main class. Main class (Test.php): <?php error_reporting(E_ALL); class Test { public $egg; public function __construct() { $this->getInstances(); $this->egg->msg("Hello!"); // line 11 } public function getInstances($folder = null) { if($folder != null) { foreach(glob("$folder/*.php") as $file) { require_once $file; $class = basename($file); if(class_exists($class)) { $lclass = strtolower($class); if(property_exists($this, $lclass)) { $this->$lclass = new $class(); } } } } else { foreach(glob("*.php") as $file) { require_once $file; $class = basename($file); if(class_exists($class)) { $lclass = strtolower($class); if(property_exists($this, $lclass)) { $this->$lclass = new $class(); } } } } } } $test = new Test(); ?> Sample class (Egg.php): <?php class Egg { public function msg($msg) { echo $msg . chr(10); } } ?> What it outputs: Fatal error: Call to a member function msg() on a non-object in Test.php on line 11 What I want it to output: Hello!
-
I'm writing some classes right now for a website with a shopping cart. There are all kinds of classes, Blog, Cart, Product, Database, etc. I am trying to make a design choice about where to store the requested quantity for a particular product. I feel like it should NOT go into the Product class, because the requested quantity does not semantically relate to any of the standard product detail. I was considering maybe setting the quantity property of the product instance, to the requested quantity, once it is put into the cart. For some reason my instinct says no, that it should be abstracted out, perhaps into the Cart class. If that is the case, how do you couple the requested quantity with the requested object? As array key/value pair? Is there another class it could go into? Does anyone have practical experience to shed some light on this?
- 6 replies
-
- shopping cart
- class
-
(and 2 more)
Tagged with:
-
I have created a class to build up the content in my page. I want to use this a broad as possible. Where I run into, is how to enclose certain content within (for example) a div, without the need for calling a closing tag. Below is a section of my class, which does the following: __construct -> Creates the "<article>" section (closed when ->Display() is called). This to keep each section in their own <article> tag AddHeader -> creates the header within the <article> AddContent -> creates the div in which all the content should be kept. Display -> closes the <div> and </article> and allows it to be echo'd. What I don't want is to keep calling the AddContent for every piece of content, but would like to add the content via various options like 'AddGraph', 'AddTable', which will be added to the content section. Also besides the header, potential tabs could be added, so adding the <div> after the header tag is not an option. Any good suggestions and/or source which would help me further? With kind regards Ralf <?php class PageContent { var $content; function __construct($class= NULL) { $this->content = "\n<article". (!empty($class) ? " class='". $class ."'" : "") .">\n"; //$this->content = "\n<div". (!empty($class) ? ' class=\"$class\"' : '') .">\n"; } function AddHeader($naam, $class= NULL){ $this->content .= "<header><h3". (!empty($class) ? " class='". $class ."'" : "") .">". $naam ."</h3></header>\n"; } function AddContent($class= NULL){ $this->content .= "<div". (!empty($class) ? " class='". $class ."'" : "") .">\n"; } function Display() { $this->content .= "<div class='clear'></div>\n"; $this->content .= "</div>\n"; $this->content .= "</article>\n"; return $this->content; } } ?>
-
In my DB class i have a function to do a simple sanitize operation. The function does three things: 1. checks weather the input variable is a integer, if it is then it gets the int value of the variable and returns it. 2. checks weather the input variable is a string, if it is then it escapes it and returns it. 3. if it is neither an integer or a string then the variable is unset and returns a "Variable deleted" message. function sanitizeData($dbc, $input){ if(is_int($input)){ $input = intval($input); return $input; } elseif(is_string($input)){ $input = mysqli_real_escape_string($dbc, $input); return $input; } elseif(!is_int($input) OR !is_string($input)){ unset($input); return "Variable contents unknown, variable deleted!"; } } I wanted other peoples ideas, opinions and suggestions on this function and what you think of it Thanks
-
Hi everyone, I can't pin down why an auto responder isn't being sent using an email class that has previously worked fine. I've tested the mail() function and it's fine so I'm presuming it's not the server (though I have contacted the host to check on recent changes). Here's an example of the ajax we're using to process everything... // EXPRESS INTEREST case "expressInterest": // Make sure the user is logged in if(!isCrewLoggedIn()) { $return["message"] = "Your session has expired"; send(); } // Make sure all required fields are present $required = array("event_id", "crew_id"); if(missingFields($required, $missing_fields)) { // Fields are missing $return["message"] = "The following fields are missing: " . arrayToErrorString($missing_fields); send(); } // All fields are present and accounted for. //require_once("classes/producer.class.php"); require_once("classes/event.class.php"); require_once("classes/email.class.php"); //Load the event object for the current event_id $objEvent = new Event($conn); $event = $objEvent->get($_POST["event_id"]); $_POST["eventname"] = $event->eventname; $_POST["eventdate"] = $event->eventdate; $_POST["eventstate"] = $event->eventstate; $_POST["eventlocation"] = $event->eventlocation; // Add the application into the database $event_id = $objEvent->addApplication($_POST); if(!$event_id) { $return["message"] = "An error occured whilst expressing interest."; send(); } // Send the event_id back to the client. $return["event_id"] = $event_id; // Send the autoresponder $email_data = array(); $email_data["firstname"] = $_SESSION["firstname"]; $email_data["surname"] = $_SESSION["surname"]; $email_data["email"] = $_SESSION["email"]; $email_data["event_id"] = $_POST["event_id"]; $email_data["eventname"] = $event->eventname; $email_data["eventdate"] = $event->eventdate; $email_data["eventstate"] = $event->eventstate; $email_data["eventlocation"] = $event->eventlocation; //send to Producer $objEmail = new Email($conn, ABSOLUTE_PATH . "email_templates/expressInterest_crew.xml", $email_data); $objEmail->sendEmail($email_data); //send to HQ too $objEmail = new Email($conn, ABSOLUTE_PATH . "email_templates/expressInterest_sc.xml", $email_data); $objEmail->sendEmail($email_data); // Everything processed OK $return["status"] = "OK"; break; And here's the email class <?php class Email { private $conn; // Database connection private $template; // The template file to use private $email_data; // An associate array containing email data private $doc; // An XML document object private $subject; // The email subject private $from; // Who the email is from private $recipients; // An array containing all recipient email addresses private $message; // The plain text or HTML message to send private $isHTML; // Set to true if this should be send as a HTML email message public function __construct($conn, $template, $email_data) { // Class constructor // Set class variables $this->conn = $conn; $this->template = $template; $this->email_data = $email_data; $this->recipients = array(); $this->isHTML = false; // Default to plain text. } public function sendEmail($data) { // Load and parse the XML email template file if(!$this->loadTemplate()) { return false; } // Compose the EMAIL from header $headers = "FROM: " . $this->from . "\r\nReply-To: " . $this->from; // Send the email to all recipients designated in the XML file. foreach($this->recipients as $recipient) { mail($recipient, $this->subject, $this->message, $headers); } // All done. return true; } private function replaceTemplateVars($xml) { if(!is_array($this->email_data)) { return; } foreach($this->email_data as $key => $value) { $xml = str_ireplace("{" . $key . "}", $value, $xml); } return $xml; } private function loadTemplate() { if(($this->template == "") || (!file_exists($this->template))) { return false; } // Load the xml template $xml = file_get_contents($this->template); // Replace any placeholder variables that with values defined in // the email_data array. $xml = $this->replaceTemplateVars($xml); // Create a new XML document from the XML data. $this->doc = new DOMDocument(); if(!$this->doc->loadXML($xml)) { return false; } // Email Subject $node = $this->doc->getElementsByTagName("subject"); if($node->length != 1) return false; $this->subject = trim($node->item(0)->textContent); // Email From $node = $this->doc->getElementsByTagName("from"); if($node->length != 1) return false; $this->from = trim($node->item(0)->textContent); // Email Message $node = $this->doc->getElementsByTagName("message"); if($node->length != 1) return false; $this->message = trim($node->item(0)->textContent); // Recipients $node = $this->doc->getElementsByTagName("recipient"); if($node->length == 0) return false; for($r = 0; $r < $node->length; $r++) { $this->recipients[] = trim($node->item($r)->textContent); } // All done - the template has been loaded and parsed. return true; } } Everything is working fine except for the autoresponder. I have also tested by placing a basic mail() function directly after the db queries and it send perfectly. I'm not great at php but I've got this far without probs and this has got me stumped. If the complete files are needed, message me and I'll email. Any help would be hugely appreciated. Cheers