PHP - Whats The Deal With Var In Classes?
Hey guys when we make a class and you see:
var myName;var myAddress;() do we still need the var? or have they removed it? Thanks! Similar TutorialsI've been wasting time reinventing the wheel with this one so I'd greatly appreciate if people here could share how they deal with this. So heres an example class:
class VarDataClass { private $module = 'show_vars'; public $category = 'DEFAULT CATEGORY'; public $title = 'DEFAULT TITLE'; public $option2 = 'DEFAULT VALUE'; public $show = 'SOMETHING'; public $output = 'box'; public $_settings = array( 'category' => 'DEFAULT CATEGORY', 'title' => 'DEFAULT TITLE', 'option2' => 'DEFAULT VALUE', 'show' => 'SOMETHING', 'output' => 'box' ); public function __constructor($options = array()) { } // some functions }So the $options parameter in the constructor contains all the custom settings for the class instance, lets say in this case they're all optional. Since they're all optional I made that $_settings array have default values. And for this example, I added another way I could do it, by adding the variables individually rather than as part of the settings array. So I'm wondering whats the best way to replace the default values with any values that the user happens to input. Is a list of variables easier, or is the $_settings array the way to go? I think the settings array would be the way to do it, so I'm thinking I should make some option setter function, but whats the easiest way to do that? Should I loop through every key in the settings array, and check if that key is present in the $options variable that the user input? Or is there some kind of array_replace function I can use that will set all the options in one go without having to use a loop? Another issue is its a pain in the ass for the user to input an associative array, its much easier to just to $object = new VarDataClass('CATEGORY','TITLE');etc. but then the problem is if they only want to set say the two last options, they'd have to do VarDataClass('','','','SHOW','OUTPUT');Basically I'm just looking for the most evolved way to handle these optional functions so I don't have to reinvent the wheel myself. Edited by entheologist, 29 August 2014 - 10:55 AM. 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. I built a website that has multiple users accessing it at once, there is a problem with the sessions. People are getting directed to a logged out page. I know why this is because I don't thoroughly understand how to use sessions.
I have picked up about storing in places other than /tmp , I'm concerned about storage and not carrying it from one page to the next
So when a person logs in, then they hit back on their browser or exit it (for a phone) and go back to it, they should still be logged in. That doesn't happen, they are usually logged out.
Also there is a weird anomaly. When I use the website on my device (phone) I don't have a problem of session value getting lost and the website exists on a server / computer that is not this phone, so why does my friend have problems with sessions but not me?
This is my general session code, it is garbage
<?php ob_start(); session_start(); if( !isset($_SESSION['last_access']) || (time() - $_SESSION['last_access']) > 60 ) $_SESSION['last_access'] = time(); session_save_path('/home/admin2/public_html/sesh'); ini_set('session.gc_probability', 1); $userrname = $_SESSION["user"]; $_SESSOIN["user"]=$userrname; if (empty($userrname)){ header("Location: "); } ?>I'd appreciate any help. Thank you. 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? So im using textwrangler and usually when you click on the '{' or '}' it will highlight everything inbetween them, well on the top one on line 7 it does not, and i tried messing around with it to try to get it to work cause i keep getting an error on line 8 that says "Parse error: syntax error, unexpected '{' in /home/truckste/public_html/create_topic_parse.php on line 8" Code: [Select] <?php if($username){ header("Location: index.php"); exit(); } if(isset($_POST['topic_submit'])){ if (($_POST['topic_title'] == "" && ($_POST['topic_content'] == "")){ echo "You Did Not Fill In Both Fields. Please Return To The Previous Page."; exit(); } else{ requre('scripts/connect.php'); $cid = $_POST['cid']; $title = $_POST['topic_title']; $content= $_POST['topic_content']; $creator = $_POST['uid']; $sql = "INSERT INTO topics (category_id, topic_title, topic_creator, topic_date, topic_reply_date) VALUES ('".$cid."', '".$title."', '".$creator."', now(), now())"; $res = mysql_query($sql) or die(mysql_error()); $new_topic_id = mysql_insert_id(); $sql2 = "INSERT INTO posts (category_id, topics_id, post_creator, post_content, post_date) VALUES ('".$cid."', '".$new_topic_id."', '".$creator."', '".$content."', now())"; $res2 = mysql_query($sql2) or die(mysql_error()); $sql3 = "UPDATE categories SET last_post_date=now(), last_user_posted'".$creator."', WHERE id='".$cid."' LIMIT 1"; if (($res) && (res2) && (res3)){ header("Location: view_topic.php?cid".$cid."$tid=".$new_topic_id) } else{ echo "There Was A Problem Creating Your Topic. Please Try Again."; } } ?> Hi Friends,
I wanted to know what is new in PHP version 5.6.0. How is it different from its previous versions? How will benefit the security of PHP websites?
Thanks in advance.
Hi again, Here is the code $string .= (substr($string,-1) == '-') ? '' : '-'; I know what this code does but to increase my knowledge could some one tell me what is the question mark symbol for ( ? ) and what is the colon doing. As I have seen the ? in a lot of scripts but have no clue what it does and what its used for cheers! Its a page 'Downloads'. Works great at localhost but doesnt show up @ web hosting. Code: [Select] <?php define('IN_PHPBB', true); $page = !isset($_GET["page"]) ? "None" : $_GET['page']; $phpbb_root_path = (defined('PHPBB_ROOT_PATH')) ? PHPBB_ROOT_PATH : './'; $phpEx = substr(strrchr(__FILE__, '.'), 1); include($phpbb_root_path . 'common.' . $phpEx); // Start session management $user->session_begin(); $auth->acl($user->data); $user->setup(); page_header('Downloads'); if(strcmp($page,"org") == 0) { $template->set_filenames(array('body' => 'download/org.html',)); } else if(strcmp($page,"audi") == 0) { $template->set_filenames(array('body' => 'download/audi.html',)); } else if(strcmp($page,"bmw") == 0) { $template->set_filenames(array('body' => 'download/bmw.html',)); } else if(strcmp($page,"vw") == 0) { $template->set_filenames(array('body' => 'download/vw.html',)); } else if(strcmp($page,"nissan") == 0) { $template->set_filenames(array('body' => 'download/nissan.html',)); } else if(strcmp($page,"opel") == 0) { $template->set_filenames(array('body' => 'download/opel.html',)); } else if(strcmp($page,"ford") == 0) { $template->set_filenames(array('body' => 'download/ford.html',)); } else if(strcmp($page,"chevrolet") == 0) { $template->set_filenames(array('body' => 'download/chevrolet.html',)); } else if(strcmp($page,"other") == 0) { $template->set_filenames(array('body' => 'download/other.html',)); } else { $template->set_filenames(array('body' => 'download/org.html',)); } make_jumpbox(append_sid("{$phpbb_root_path}viewforum.$phpEx")); page_footer(); ?> and the html: Code: [Select] <table class="tablebg" cellspacing="1" width="100%"> <tr> <th>BMW</th> </tr> <tr class="row1"> <td align="center" style="padding:5px 5px 5px 5px;"> <center> <hr width="60%" size="3" /> <table width="70%"> <tr> <td width="10%"><a href="http://www.upload.ee/image/1626514/325i_2.jpg" target = "_blank"> <img src="http://www.upload.ee/thumb/1626514/325i_2.jpg" border="0"/></a> <a href="http://www.upload.ee/image/1626518/325i_3.jpg"> <img src="http://www.upload.ee/thumb/1626518/325i_3.jpg" border="0"/></a> <td width="0%"><a href="http://www.upload.ee/image/1626519/325i_1.jpg" target = "_blank"> <img src="http://www.upload.ee/thumb/1626519/325i_1.jpg" border="0"/></a> <a href="http://www.upload.ee/image/1626521/325i_4.jpg" target = "_blank"> <img src="http://www.upload.ee/thumb/1626521/325i_4.jpg" border="0"/></a></td></td> <td><b><font color="white">Name:</font></b> 1996 BMW 325i e36 Convertible</br> <b><font color="white">Original Author:</font></b> ikey07</br> <b><font color="white">Size:</font></b> 3.89MB</br></br> <b><font color="white">Description:</font></b></br> Tunable in WAA</br> 2 Body kits included</br> 1. BMW M e36 series + Hood Vents</br> 2. BMW M e46 series + Masked Lights</br> New 2 M series wheels e36/e46</br> Realistic heavy damaged model</br> Model accuracy as real car 96%</br> Openable petrolcap</br> If you replace this car as BF Injection, the front fan is working ( spining )</br></br> <a href="http://ikey07.c-rp.net/viewtopic.php?f=6&t=2"><b><font color="white">Comments</font></b></a></br> </br> <ul id="nav"> <a class="downl" href="http://ikey07.c-rp.net/download/1996_BMW_325i_e36.rar" title="Download"><span>{L_DOWN}</span></a> </div> </br> </td> </tr> </table> <hr width="60%" size="3" /> </center> </td> </tr> </table> <br /> Code: [Select] $correct_numbers = 0; $correct = 0; $numbers_chosen = @explode("|",$ticket['numbers_chosed']); $your_numbers = array(); $array1 = array_count_values($numbers_chosen); $array2 = array_count_values($winning_numbers); foreach($array1 as $number1 => $count1) { foreach($array2 as $number2 => $count2) { if($number2 == $number1 and $count2==$count1) $correct_numbers += $count2; } } $use = 0; $numbers = @implode("|",$winning_numbers); echo $correct_numbers; echo "<br>"; echo $lottery['balls']; I have no idea wthell this does Code: [Select] $correct_numbers += $count2; What's that += suppose to mean? I know the $correct_numbers is supposed to be a matching array count from the for eachs right? $ticket['numbers_chosed'] is Code: [Select] 8|18|3 Cant Figure Out Whats Wrong With it.. Code: Code: [Select] <?php if(isset($_SESSION['user'])) { $bb = mysql_query("SELECT * FROM main WHERE id=". $_SESSION['id']) or die ("An error has occured: " . mysql_error()); while($n=mysql_fetch_array($bb)) { ?> <div class='cs_article'> <div class='left'> <h2>User Control Panel</h2> <p><a href="usercp.php">User CP</a><?php if($n['rights'] == 1) { echo ", <a href="modcp.php">Mod CP</a>"; }?> <?php if($n['rights'] == 2) { echo ", <a href="aa/">Admin CP</a>"; }?> <div class='button'><a href='usercp.php'>Read more</a></div> </div> <div class='right'> <h1>User CP</h1> </div> </div> <?php }} ?> What its doing: Mod-Justin Compared to Mod-Justin can you tell me whats wrong with this? Code: [Select] <?php $age= 60; if( isset($_SESSION['logedin']) ) { $q = mysql_query('SELECT id=`$id`, DATE_FORMAT(`last_activity`,"%a, %b %e %T") as `last_activity`,UNIX_TIMESTAMP(`last_activity`) as `last_activity_stamp`FROM `mymembers`WHERE `$logOptions_id` <> "'.($_SESSION['logedin']).'"'); $isonlinecheck = mysql_query($q); if ($isonlinecheck ="last_activity_stamp + $age "< time()){ $isonline = "is <font color='green'>online!</font>";} else { $isonline = "is<font color='red'> offline!</font>"; } } ?> Good evening my PHP experts!!! OK so heres the problem...I have been at this for about 2 DAYS now and for the life of me I just don't understand what I could possibly be doing wrong. I have 3 of 4 variables outputting correctly but without my id being pulled from the URL NOTHING will get written to my database. I have ran some tests and I came to learn that my $_POST['id']; function is not working properly for some strange reason. As always, any help would be greatly appreciated. Please see below PHP code. I also have posted the HTML code for your reference purposes...thanks in advance. Please helpppp!!!! Code: [Select] <?php session_start(); $id = ''; if (isset($_POST['password'])) { include_once "scripts/connect_to_mysql.php"; $id = $_POST['id']; $id = mysql_real_escape_string($id ); $id = eregi_replace("`", "", $id); $cust_password = $_POST['password']; $hashedPass = md5($cust_password); $sql = mysql_query("UPDATE customers SET password='$hashedPass' WHERE id='$id'"); $update_success = 'You have successfully updated your Password. Please click <a href="customer_login.php">HERE</a> to log into your account.'; //Output to test whether or not my variables have anything in them. //$update_success, $hashedPass, $cust_password all Output just fine. $id displays nothing at all. echo $update_success; echo $hashedPass; echo $cust_password; echo $id; exit(); } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> <link rel="stylesheet" type="text/css" href="style.css"/> <script type="text/javascript"> <!-- Form Validation --> function validate_form ( ) { valid = true; if ( document.form.password.value == "" ) { alert ( "Password field must not be blank." ); valid = false; } return valid; } <!-- Form Validation --> </script> </head> <body> <div id="pg_container"> <!--HEADER SECTION--> <div id="header"> <div id="header_logo"></div> <div id="header_right">Welcome to Built 2 Manage.</div> </div> <!--HEADER SECTION--> <!--PAGE CONTAINER--> <div id="pgbdy_container"> <form action="cust_acc_conf.php" method="post" id="form" name="form" enctype="multipart/form-data" onsubmit="return validate_form ( );"> <div id="login_header"> <p> Please log into your account below. </p> </div> <div id="cust_choose_pass_form"> <div id="cust_choose_pass_text"> <p> Password: </p> </div> <div id="cust_choose_pass_field"> <p> <input name="password" type="text" id="password" /><br /><br /> <input name="submit_password" type="submit" id="submit_password" value="Submit Password" /><br /> </p> </div> </div> </form> </div> <!--PAGE CONTAINER--> <div id="footer"></div> </div> </body> </html> Ive created a process which automatically creates a form for all of the "courses" that are listed in a database. This table shows the name, the course code, the current program the course is under and an option to delete the course. I have created a drop down menu for the user to select any of the current programs to switch the course into. My problem is I have X amount of select fields and radio buttons and I dont know how to tell which one has been changed below is my code, appreciate the help!: case "ep": if (isset ($_GET['id'])){ $id = $_GET['id']; echo "Below lists all of the current courses under this program. Once you have made all of the changes click the submit button at the bottom of the page. <br><br><br>"; $query = "SELECT * FROM courses WHERE cid = $id"; $result = mysql_query($query) or die (mysql_error()); echo "<form action=\"course_process.php\" method=\"post\">"; echo "<table><tr><td><strong>Course Name</strong></td><td><strong>Course Code</strong></td><td><strong>Change Course Program</strong></td><td><strong>Delete</strong></td></tr>"; $i = 0; while ($row = mysql_fetch_assoc($result)){ $r = $row['id']; $query2 = "SELECT * from catagories"; $result2 = mysql_query($query2) or die (mysql_error()); echo "<tr><td> ". $row['name']. " </td><td> ".$row['code']." </td><td><select name=\"".$row['id']."\">"; while ($row2 = mysql_fetch_assoc($result2)){ echo "<option value=".$row2['id'].">".$row2['name']. "</option>"; } echo "</select></td><td><input name=\"".$row['id']."\" type=\"radio\" value=\"Click to delete\" /></td></tr>"; } echo "<tr><td></td><td></td><td></td><td><input name=\"submit\" type=\"submit\" value=\"Commit Changes\" /> </td></tr></table></form>"; }else{ echo "Invalid action request. ERROR CODE 1"; } break; hi all me again i have this bit of code mysql_connect($db_hostname,$db_username,$db_password); @mysql_select_db($db_database) or die( "Unable to select database"); $whereClauses = array(); if(isset($_GET['bi'])) { $whereClauses[] = "bi=1"; } if(isset($_GET['print'])) { $whereClauses[] = "print=1"; } if(isset($_GET['online'])) { $whereClauses[] = "online=1"; } $query = "SELECT * FROM `project` ORDER BY `project`.`position` ASC "; if(count($whereClauses)) { $query .= " WHERE " . implode(" AND ", $whereClauses); } with this error msg There was a problem with the SQL query: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE online=1' at line 3 I get this kinda error a lot as im still learning is there any way to better find out whats going wrong i use error_reporting(E_ALL); ini_set('display_errors', '1'); at the start of my scripts but it dont tell me a lot. i can work out it some thing to do with the $whereClauses as the page displays ok on show all. Im bit stumped here not even sure what to call the prob is it sql query error or php array problem thanks for any help This topic has been moved to CSS Help. http://www.phpfreaks.com/forums/index.php?topic=358008.0 $search
= $_POST['search']; $replace = $_POST['replace']; $zero = 0; $gibs = mysql_query("SELECT * FROM anime"); while ($gib = mysql_fetch_assoc($gibs)) { $new_description[] = str_replace($search,$replace,$gib['description']); $new_history[] = str_replace($search,$replace,$gib['history']); $anime_id[] = $gib['anime_id']; $numberlinks = ++$zero; } for($i=0; $i<$numberlinks; $i++) { $thequery[] = mysql_query("UPDATE anime SET description = '".mysql_real_escape_string($new_description[$i])."', history='".mysql_real_escape_string($new_history[$i])."' WHERE anime_id='".$anime_id[$i]."'"); } foreach ($thequery as $query){ mysql_query($query) or die (mysql_error()); echo "<span style='color:green'>Edited sucessfully <b>Anime ".++$one."</b> </span><br/>"; } echo "<meta http-equiv='refresh' content='2;url=http://www.website.com/forums/downloads-manager.php?task=fix-descriptions'>"; output: Code: [Select] You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1' at line 1[/b] Inputs: $search: ’ $replace: " What would be the best way to break the following html into a table <div class="highlight">Name: CHRISTOPHER</div> <table summary="This table contains status information for the selected name."> <caption>Selected name status Information</caption> <tr> <th>Current Name:</th> <td>CHRISTOPHER</td> </tr> <tr> <th>Initial Filing Date:</th> <td>DECEMBER 15, 1997</td> </tr> <tr> <th>County:</th> <td>NEW YORK</td> </tr> <tr> <th>Jurisdiction:</th> <td>NEW YORK</td> </tr> <tr> <th>Type:</th> <td>Full Member</td> </tr> Would pregmatch or COMDocument be easier? Hi all, Yeah just a fresh pair of eyes needed. It just wont insert into the table and the alert returns a blank. Only thing I can think is thats its posting variables from two different queries...but that shouldnt make a difference... Cheers Code: [Select] FORM PAGE************************* //*****************************LOGGED CHECKER********************* $sql = "SELECT * FROM users WHERE firstName= '$logged'"; if ($result = mysql_query($sql)) { if (mysql_num_rows($result)) { if ($row = mysql_fetch_assoc($result)) { //**************QUESTION FORM***************************** $sql2 = "SELECT * FROM questions WHERE questionID= '$orderCounter'"; if ($result2 = mysql_query($sql2)) { if (mysql_num_rows($result2)) { if ($row2 = mysql_fetch_assoc($result2)) { echo "<p>" . $row2['questionText'] . "</p>"; echo '<form name="form1" method="post" action="questionProcess.php">'; echo '<input type="radio" name="q1" value="' . $row2['answer1'] . '" />' . $row2['answer1'] . '<br />'; echo '<input type="radio" name="q1" value="' . $row2['answer2'] . '" />' . $row2['answer2'] . '<br />'; echo '<input type="radio" name="q1" value="' . $row2['answer3'] . '" />' . $row2['answer3'] . '<br />'; echo '<input type="radio" name="q1" value="' . $row2['answer4'] . '" />' . $row2['answer4'] . '<br />'; echo '<input type="hidden" name="userid" value="' . $row['userid'] . '" />'; echo '<input type="hidden" name="orderCounter" value="' . $row['orderCounter'] . '" />' echo '<input type="submit" name="Submit" id="Submit" value="Next" />'; echo '</label>'; echo '</form>'; } } } } } } ?> PROCESSING PAGE**************************************** $q1=$_POST['q1']; $userid=$_POST['userid']; $orderCounter=$_POST['orderCounter']; // To protect MySQL injection $q1 = stripslashes($q1); $userid = stripslashes($userid); $orderCounter = stripslashes($orderCounter); $q1 = mysql_real_escape_string($q1); $userid = mysql_real_escape_string($userid); $orderCounter = mysql_real_escape_string($orderCounter); //ALERT CHECKER function confirm($msg) { echo "<script langauge=\"javascript\">alert(\"".$msg."\");</script>"; } $msg = $userid; confirm($msg); //ALERT CHECKER if ($q1 == "" ) { $wrong = '<div id="blackText"><p>Please Answer the Question<p></div>'; } else { $sql="INSERT INTO $tbl_name (userid, value, orderCounter) VALUES ('$userid', '$q1', '$orderCounter')"; $result=mysql_query($sql); } ob_end_flush(); ?> hi all, Is this line right? Im trying to say if the cookie has not been created create it and set as default value = 0 however i dont think this is right: Code: [Select] $points = $_COOKIE["points"] ? $_COOKIE['points']:0; thanks, |