PHP - Understanding Php Classes
Let's see....
You add values to variables but you can declare them before assigning a value... Loops are great - they do things until a specific criteria is met....then I exit or break out of them. Functions are code that do specific tasks (or series of tasks) & can be called upon at any given time during a script. An array is like a....hotel with many different rooms - each room being a different value. I get GET and POST...and know how to use them between pages. Sessions can be used to pass data between pages - they help to keep track of things.... Cookies are like little signatures from your script that you can give to a users browser for any number of reasons. I guess you could say I'm starting to get it. It's only been 4 months. That being said can someone give me a brief and yet simple summary of what a PHP Class is... Similar TutorialsI'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. 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? Hi, can someone help me figure out why the logo div isn't centering? Code: [Select] <?php require_once("functions.php"); ?> <!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> <style type="text/css"> td { border-top-style: solid; border-right-style: solid; border-bottom-style: solid; border-left-style: solid; border-top-color: #30C; border-right-color: #30C; border-bottom-color: #30C; border-left-color: #30C; } </style> <link href="doggyTreats.css" rel="stylesheet" type="text/css" /> </head> <body> <?php [color=yellow]logo();[/color] navBar(); echo "<div id=\"mainContent\">"; echo "<form action=\"\" method=\"post\" name=\"catalog\">"; DatabaseConnection(); $query = "SELECT * FROM treats"; $result_set = mysql_query($query) or die(mysql_error()); $i = 0; echo "<table>"; while ($row = mysql_fetch_array($result_set)) { echo"<tr><td width=\"2s00px\"><img src=\"{$row['product_pic']}\" /></td><td width=\"200px\">{$row['product_title']}.<br /><br />{$row['product_Description']}.<br /> Price: \${$row['price']}.<br /><br />Quantity <input name=\"quantity\" type=\"text\" size=\"2\" /></td></tr>"; } echo "<tr>"; echo "<td><input name=\"submit\" type=\"button\" value=\"Proceed to Checkout\" />"; echo "</table>"; echo "</form>"; echo "</div>"; footer(); ?> </body> </html> Code: [Select] #navBar { background-color: #060; width: 200px; padding-top: 50px; padding-bottom: 250px; float: left; } #navBar #menu { margin-right: 6px; } .menuOption { background-image: url(assets/bone2a.gif); background-repeat: no-repeat; padding-bottom: 25px; list-style-type: none; height: 20px; padding-top: 26px; text-align: center; } body { background-color: #0089cc; }[color=yellow] #logo { text-align: center; margin-top: 5px; height: 123px; width: 182px; }[/color] #footer { font-style: italic; text-align: center; } .shoppingCart tr th { padding: 5px; } .shoppingCart tr td { padding: 5px; } #mainContent { width: 350px; margin-top: 30px; } Code: [Select] <?php [color=yellow]function logo() { echo "<div id=\"logo\">"; echo "<img src=\"assets/logo.gif\" alt=\"logo\" />"; echo "</div>"; }[/color] function footer() { echo "<div id = \"footer\">"; echo "Auntie Vic\'s Treatery <br />"; echo "PO Box 34092 <br />"; echo "Clermont, IN 46234 <br />"; echo "317-701-0343 <br />"; echo "<a href=\"mailto:auntievics@gmail.com\">Email Us</a>"; echo "</div>"; } function navBar() { echo "<div id = \"navBar\">"; echo "<ul id=\"menu\">"; echo "<li class=\"menuOption\"><a href=\"index.html\">Home</a></li>"; echo "<li class=\"menuOption\"><a href=\"aboutUs.html\">Management Team </a></li>"; echo "<li class=\"menuOption\"><a href=\"treats.html\">Treats </a></li>"; echo "<li class=\"menuOption\"><a href=\"charities.html\">Supported Charities</a></li>"; echo "<li class=\"menuOption\"><a href=\"order.html\">Orders</a></li>"; echo "</ul>"; echo "</div>"; } ?> I have a system that I want to change. I'm attempting to convert a huge project I made with mysql to PDO. I have many cases where I would use a WHILE statement to return a query array. Code: [Select] while($row= mysql_fetch_array($result)){From what I've seen so far, it looks as though I need to use a foreach statement to do the same task. Code: [Select] foreach ($dbh->query($sql) as $row){ Is that correct? Can someone explain to me in plain English what is the purpose of imagecreatefromgif?? I read the Manual but am not really understanding what purpose it servers in the larger image rendering process. Also, how should I Error-Handle this function - if at all?! Thanks, Debbie Hey guys. I have this code which connect me to the database and displays info in the web. However i do not understand a few lines of it. Code: [Select] <?php while ($query = mysql_fecth_assoc($result)) { $field01 = $result['Name']; $field02 = $result['Username']; ?> Can someone try to explain in they're own, simple words? Thank you. Full code. Code: [Select] <?php $dbhost = ""; $dbuser = ""; $dbpass = ""; $db = ""; $connection = mysql_connect($dbhost, $dbuser, $dbpass); mysql_select_db($db, $connection); $query = 'SELECT * FROM users'; $result = mysql_query($query); while ($query = mysql_fecth_assoc($result)) { $field01 = $result['Name']; $field02 = $result['Username']; echo $field01; echo $field02; } ?> So I have been around the net a few times reading tutorials, watching vids as I try to teach my self php. I have come across a few items that I am having trouble understanding. The first is the use of the % symbol. For example I commonly see the % used in generating random strings of characters. Here is piece of the code I used to generate a random string. What is the purpose of % in this statement. if ($alt == 1) { $rndPKID .= $consonants[(rand() % strlen($consonants))]; $alt = 0; } else { $rndPKID .= $vowels[(rand() % strlen($vowels))]; $alt = 1; } The second is the use of the & or as it is better known. The ampersand symbol. I commonly see it used when declaring a function. function newfunction($var1, &$var2){ //Do Stuff Here. } Can anyone help me understand those 2 symbols purpose and usage in php? Hi i'm new to the forum and i'm wondering if anyone here could help me out with the problem i'm having. the script i have uses $_SESSION['userid'] = $users['id']; and i'm not exactly sure how to read that .. any information would be helpful. thanks in advance Hi.
I've been trying to understand the concept of password_hash but so far it has eluded me!
registration
<?php if(isset($_POST['submit'])){ $name = $_POST['name']; $email = $_POST['email']; $password = $_POST['password']; //$pass_hash = PassHash::hash($_POST['password']); $hash = password_hash($password, PASSWORD_BCRYPT); $stmt = $pdo->prepare("INSERT INTO hash_test(name, email, password) VALUES(:name, :email, :password)"); $stmt->execute(array( ':name' => $name, ':email' => $email, ':password' => $hash )); if ($stmt->rowCount() ==1){ echo "Registration Successful"; }else{ echo "There was a problem taking your request"; } } ?>The registration is working fine and all fields are inserted. The problem is when loggin in, its giving me an error : unknown variable which is the $hash. The verify parameter is thus: password_verify($password, $hash) I believe the $password is the users password for login, now how/when/where do assign a value to $hash? since in my db i have email(username) password. Do i need to store the hash separately on the db? Can someone please enlighten me more my login code <?php if(isset($_POST['login'])){ $password = $_POST['password']; $stmt = $pdo->prepare("SELECT email, password FROM hash_test WHERE email=:email AND password=:password"); $stmt->execute(array( ':email' => $_POST['email'], ':password' =>$password )); //if ($stmt->rowCount() ==1){ if (password_verify($password, $hash)) { /* Valid */ echo "Right"; } else { /* Invalid */ echo "wrong"; } //} } ?>THANKS Hi All I have a basic login system on my site. How would I go about displaying the current logged in user information from the session Id. its quite confusing..... <?php require 'Mysql.php'; class Membership { function validate_user($un, $pwd) { $mysql = New Mysql(); $ensure_credentials = $mysql->verify_Username_and_Pass($un, ($pwd)); if($ensure_credentials) { $_SESSION['status'] = 'authorized'; header("location: ../selfbuild/Controlpanel.php"); } else return "Please enter a correct username and password"; } function log_User_Out() { if(isset($_SESSION['status'])) { unset($_SESSION['status']); if(isset($_COOKIE[session_name()])) setcookie(session_name(), '', time() - 1000); session_destroy(); } } function confirm_Member() { session_start(); if($_SESSION['status'] !='authorized') header("location: login.php"); } } Just need to display the user name at the moment but am kinda not getting how its done. Do I just need <?php session_start(); echo $un Hi guys Sorry i keep asking noob questions today... I'm working on something that has a user facing image upload facility. So i'm slowly working through a class to make this as secure as possible. One of the tips online is to use the method "is_uploaded_file ( )". According to php.net - "Returns TRUE if the file named by filename was uploaded via HTTP POST. This is useful to help ensure that a malicious user hasn't tried to trick the script into working on files upon which it should not be working--for instance, /etc/passwd. " I'm not one to just use things without understanding why. So how exactly could someone get a script to work on an internal file via a browse/upload facility? I don't really understand what htmlentities() does and when to use it?! The manual says this... <?php $str = "A 'quote' is <b>bold</b>"; // Outputs: A 'quote' is <b>bold</b> echo htmlentities($str); // Outputs: A &#039;quote&#039; is <b>bold</b> echo htmlentities($str, ENT_QUOTES); ?> 1.) Isn't there a way to print this... Code: [Select] $str = "A 'quote' is <b>bold</b>"; ...as this... Quote A 'quote' is <b>bold</b> That is, WYSIWYG. 2.) When and why would you want this displayed... Quote A 'quote' is <b>bold</b> I am trying to make my code more secure, and I was told to use something like this on all code that comes from the User and needs to be output, but I'm a little lost here... echo ' <div class="userInfo"> <a href="#" class="username"> <strong>' . nl2br(htmlentities($username)) . '</strong> </a>'; Debbie I have been struggling with understanding sessions and I think I finally understand it, but I want to make sure. Say you had a catalog page with products and A quantity text field. the session code would be something like this: Code: [Select] session_start(); $_SESSION ['product_id']=$product_id; $_SESSION ['quantity']=$quantity; that code would go on the catalog page and the checkout page, right? The only thing I'm not quit clear on is what goes in the [] I need some help understanding the below syntax (the ? and the colon are throwing me) isset($_POST['cardType']) ? $_POST['cardType'] : ''; Thanks for any help on this .. Frank Hello, After a user gets input into my Users table in my database, I'm using lastInsertId() to grab the newly created ID and then enter the newly created ID (along with some other stuff) into a separate table. Could this potentially be a problem? In other words, what happens if 2 users on 2 different computers both sign up a the same time? How will be database know which lastInsertId() to use? Here's my current code: $dbWrite->insert('users', $data); $last_id = $dbWrite -> lastInsertId(); // get the ID that was just created $data = array ('course_id' => $_POST['course_id'], 'user_id' => $last_id); $dbWrite->insert('course_enrollment', $data); // Use that new ID in a different table Perhaps there's a way to combine the steps? Thank you for your thoughts... Code: [Select] $result = mysql_query("SELECT * FROM Chords_Loops_Lyrics ORDER BY MusicFiles_ID ASC"); while($row = @mysql_fetch_array($result)){ $Chords_Loops_Lyrics = array($row['CCL_ID'] => $row['MusicFiles_ID'], $row['Type'], $row['FileName']); } I know I'm doing this wrong, because of the results. How can I assign values to this array, when I do a print r on this, it only spits out the last value. I need to store like 100 of these "chord loops and lyrics" into an array with the values you see in the $row fields. I just can't seem to find how to properly write this in php. Hi All, I'm trying to understand the logic behind this bit of code I found. I (think I) get that it takes an argument which in this case is a number, an checks to see if the array isset, then uses a while loop to loop through the possible values taking each value and placing it into another function which performs some task. What I'm really confused about is how the code is using unset, If I'm correct it's unsetting the incremented value which is the value that should be used in the next iteration, now I know this is not the case, but I don't understand why this is working. I have included the code in the topic and I also wrote a small piece of code to mirror this so I could play around with it in hopes of understanding the logic but it gives me a syntax error in my IDE when I try to unset the incremented value. I know this is probably something really stupid so be kind. <?php define("NUM_0", 0); define("NUM_1", 1); define("NUM_2", 2); define("NUM_3", 3); define("NUM_4", 4); function function_1($position) { static $positions = array(NUM_0, NUM_1, NUM_2, NUM_3, NUM_4,), $index = 0; if (isset($positions[$index])) { while ($position >= $index) { $current_position = $positions[$index]; unset($positions[$index++]); function_2($current_position); } } } function function_2($position) { switch ($position) { case 0: echo '$position equals 0 <br />'; break; case 1: echo '$position equals 1 <br />'; break; case 2: echo '$position equals 2 <br />'; break; case 3: echo '$position equals 3 <br />'; break; case 4: echo '$position equals 4 <br />'; break; } } function_1(NUM_4); [b] [u]output![/u] $position equals 0 $position equals 1 $position equals 2 $position equals 3 $position equals 4 [/b] function test() { static $var_1; $var_1 = 10; if (isset($var_1)) { while ($var_1 >= 0) { $var_2 = $var_1; unset ($var_1++); // syntax error on this line. echo $var_2; } } } test(); ?> I come from a long line of down to earth, hard-up, and linear programmers and I've been introduced to the wonders of web. But now I'm a bit lost. Okay, I know much about programming concepts with experience with C++, C#, and assembly, but I can't seem to tame PHP. I've written some code to act as a sort of framework in the spirit of the M-V-C pattern, but I don't know what's happening to my instantiations! I've been reading up on the help files, documentations, and looking up excellent code, but I still don't know what's happening. I'm totally in the dark. Can someone point me to the light? I create my includes (global variables), and local variables, and even classes, but I seem to lose the instantiation of these objects when I navigate more than three pages from my index. What's happening and how do I avoid this? Hi.
I haven't done a lot of OOP. Hardly any really. I've had a go at writing a very small class that outputs a greeting depending on what time of day it is. What do the OOP experts here make of it? What do you like, what do you hate? Is there anything I could do to make it more useful?
Here is the code;
class Greeting { // the __construct didn't do what I originally wanted. Denfine the hour outside the method (I don't know why this is a good/bad idea) /* public function __construct() { $hour_of_day = date('G'); } */ public function callGreetingPhrase() { return $this->getGreetingPhrase(); } // the setter doesn't seem to have a purpose here. I tried using it so that I could pass in a value of my choosing (for testing purposes) can't get it to work though /* public function setGreetingPhrase($value) { $this->hour_of_day = $value; } */ private function getGreetingPhrase() { $hour_of_day = date('G'); if($hour_of_day < 12 ) { // if it's before 12pm $greeting_phrase = "good morning"; } elseif($hour_of_day >= 12 && $hour_of_day < 18 ) { // if it's after 12pm but before 6pm $greeting_phrase = "good afternoon"; } else { // what is left over - after 6pm until midnight $greeting_phrase = "good evening"; } return $greeting_phrase; } } $greeting = new Greeting; echo $greeting->callGreetingPhrase();It annoyed me that I could 't figure out how to use the __constructor here to store the hour. But should that have bothered me? Can someone maybe explain a bit about the setter that I tried to use setGreetingPhrase. I only put it in because I've seen other Classes with one. Could I use a setter method here for anything useful? Any feedback appreciated! |