PHP - Problem With Constructor
Hello All, I have been having a problem recently with a constructor function that is responsible for encrypting the password every time a user logs in or creates a new account. I am using PHP OOP and the constructor function belongs to the user class. I have included the snippet below: ********************* function __construct($encrypt_pass) { $this->password = sha1($encrypt_pass); } ********************* I have the following code in the head of my register form which calls the create function once everything has been verified: <?php if ((isset($_POST['register'])) && ($_POST['email']) == ($_POST['email_verify'])) { $username = trim($_POST['username']); $password = trim($_POST['password']); $email = trim($_POST['email']); $first_name = trim($_POST['first_name']); $last_name = trim($_POST['last_name']); $create_new_user = new User($password); $create_new_user->username; $create_new_user->password; $create_new_user->email; $create_new_user->first_name; $create_new_user->last_name; $create_new_user->create(); $message = "Please check you inbox and follow the instructions to verify your account; Otherwise it will be deleted after seven days."; } elseif ((isset($_POST['register'])) && ($_POST['email']) != ($_POST['email_verify'])) { $message = "The email addresses did not match! Please enter them again."; } else { $username = ""; $password = ""; $email = ""; $email_verify = ""; $first_name = ""; $last_name = ""; } ?> ****************************** I'm not sure if I'm using the constructor correctly or not. When I instantiate the object it will give me an error unless I pass in the $password variable, $create_new_user = new User($password);, but every time I do it fails to input the other fields into the database. I know the create function is working correctly because I commented out the constructor and removed the $password variable from the initial object call and everything worked fine. Please let me know what I am doing wrong. Any help would be very much appreciated. Similar Tutorialsclass 1: class HelloWorld { public $world; function getHtml() { return "<html><body>". "Hello, ".$this->world."!". "</body></html>"; } } class2: class HelloWorld { public $world; function __construct($world) { $this->world = $world; } function getHtml() { return "<html><body>". "Hello ".$this->world."!". "</body></html>"; } } i don't know why in class 2 it uses a construct function. i feel it is unnecessary .any tips would be appreciated. Hello all, I have been trying to create a new constructor function using OOP PHP that will automatically encrypt passwords before they are sent to the database. However, I am not sure if my understanding of constructors is wrong if I am just not doing it right. As I understand it a constructor function will allow you to perform an operation on an object before the object is used. I have included some snippets of my code and would appreciate any insight on this matter: Code from the User object is below: function __construct($encrypt_pass) { $this->password = $encrypt_pass; } public function new_user() { $create_new_user = new User(); if(isset($create_new_user->id)) { $create_new_user->update(); } else { return false; } } public static function authenticate($username="", $password="") { global $db; $username = $db->escape_value($username); $password = $db->escape_value($password); $sql = "SELECT * FROM users "; $sql .= "WHERE username = '{$username}' "; $sql .= "AND password = '{$password}' "; $sql .= "LIMIT 1"; $result_array = self::find_by_sql($sql); return !empty($result_array) ? array_shift($result_array) : false; } The following code is from the administrative script to create a new user: <?php if(isset($_POST['submit'])) { $create_new_user = new User(); $create_new_user->username = trim($_POST['username']); $create_new_user->password = trim($_POST['password']); $create_new_user->first_name = trim($_POST['first_name']); $create_new_user->last_name = trim($_POST['last_name']); $create_new_user->email = trim($_POST['email']); if($create_new_user && $create_new_user->create()) { $session->message("echo $username has been successfully added as a new us$ redirect_to("index.php"); } else { $message = "There was an error while creating the new user. Please contact$ } } else { $username =""; $password =""; $first_name=""; $last_name=""; $email=""; } ?> The following snippet is from the login page: if (isset($_POST['submit'])) { $username = trim($_POST['username']); $password = trim($_POST['password']); $found_user = User::authenticate($username, $password); if ($found_user) { $session->login($found_user); log_action('Login', "{$found_user->username} logged in."); redirect_to("index.php"); } else { $message = "Username/password combination incorrect."; } } else { $username = ""; $password = ""; } ?> Since I am using the sha algorithm built into PHP I figured it would be best to build it into the object so it would occur automatically. If I have a base class MyBase: Code: [Select] class MyBase { public $user_id = NULL; public function __construct() { $this->user_id = "justin"; } } Then I have a class which inherits the base class MyClass: Code: [Select] class Test extends MyBase { public static function get_user_id() { echo parent::$user_id; } } Finally calling it: Code: [Select] echo Test::get_user_id(); First question, do I have to create an instance of MyBase, or when Test extends MyBase will it instanciate it automatically and call the MyBase constructor? Second, I am getting the error: PHP Fatal error: Access to undeclared static property: MyBase::$user_id Hi, I need some help with php using class and constructor, this is stuff I am familiar with with Java but not in PHP, so I can't get the code to run. please see code below: ================ Code: [Select] <?php $array1=array(""); $array2=array(""); $binary=1; class Foobar { /*Toy FCN that will append "dog" to 1 and "cat" to -1*/ //param numRuns is how many times to run this FCN function putInProperArray($numRuns) { for($i=0;$i<$numRuns;$i++) { if($binary==1) $array1=$array1." dog <br />"; else if($binary==-1) $array2=$array2." cat <br />"; $binary*=-1; } } $fooBar=new Foobar(); $fooBar->putInProperArray(3); } ?> I just want it to store appended "dog" or "cat" string to array1 or array2, just a random function I made up. Please help, thanks. void __construct ([ mixed $args [, $... ]] ) What is the "void" in the above code? (It looks like Java?!) TomTees I am calling my class constructor with the following code class controller{ function _construct($name,$pass){ session_start(); get_model_class($name, $pass); echo "I\'m in controller"; } } function get_model_class($username, $password){ $my_model = new model(); $my_model->check_users($username,$password); } $username = $_POST['username']; $password = $_POST['password']; echo "in controller.php"; $newUser = new controller($username,$password); but it is not entering the constructor Hi, I'm new here and got a very specific PHP question. I got the following code: Code: [Select] <?php class Foo { } class Bar { private $foo; private $string; public function __construct( $string = 'abc', $foo = new Foo() ) { $this->string = $string; $this->foo = $foo; } } $bar = new Bar(); ?> It gives me an "unexpected T_NEW" syntax error for the line Code: [Select] public function __construct( $string = 'abc', $foo = new Foo() ) { I know I can use something like this, although it's a rather ugly workaround: Code: [Select] public function __construct( $string = 'abc', $foo = null ) { if( is_null($foo) ) { $foo = new Foo(); } $this->string = $string; $this->foo = $foo; } But my question is, why is it not allowed to create a new object as a default for a parameter in the constructor? Thanks in advance! So I have this class: Code: [Select] <?php class page { private $title; function __construct(){ //note: This code snippet (below) does not appear to be having the desired effect of //running the PHP code on page declared by p if(!isset($_GET['p'])) : include("../content/home.php"); else : include("../content/{$_GET['p']}.php"); endif; /////////////////////////////////////////////// } public function setTitle($t) { $this->title=$t; }?> and I need the following from the content page (the page declared by $_GET['p']) to be ran in the constructor: Code: [Select] <?php global $page; $page->setTitle("About Us"); ?> this is in order to set the page title, so I can use it elsewhere. I hope my explanation (although fairly vague), is somewhat clear. Any help on this? I was told that using <<<EOF would be a potential requirement? but I am completely unfamiliar with that method. Long story short, I have a class that does some data verification and session management. In order to do some of this verification, it needs a database connection. I am using the MDB2 class; here is a sample of the constructor's code: this is a snippet of code from My Class. // FUNCTIONS function __construct() { /* other code here */ // set up our datbase connection global $dsn; // must use global as to include the one *from* the settings.php include $mdb2 =& MDB2::singleton($dsn); if (PEAR::isError($mdb2)) { die("<H1> THERE WAS AN ERROR </H1>" . $mdb2->getMessage()); } echo("SESSION CLASS: if you see this, then we're goood!"); // some very crude debugging, please ignore this! } Now, i have another function within this same class: public static function data_validateUserName($safeUserName){ // build the query $q = "SELECT uName FROM Users WHERE username = '$safeUserName'"; $result = $this->$mdb2->query($q); if($result->numRows() >= 1){ // there is 1 or more hits for a username, it is not available! return false; } else if ($result->numRows() < 1){ // there is less than 1 row with that username, we're golden! return ture; } } Inside the constructor, i have correctly set up a MDB2 object. I was able to run some queries and other things on it *inside* the constructor. Because of this, i know that it's settings are correct and it is fully working. However, when i try to use that $mdb2 object inside this other method, i get all sorts of errors about that being a bad reference to an object that essentially does not exist. Now, i tried searching here, and didn't get much help, so apologies. If you've got a link to a similar question, then please post that with a brief explanation of what you searched for to get it... Also, the php.net manual is not very helpful about the scope of objects in this particular setup... so please know that i did pour over that before posting here. Thanks for your time, all. ***** EDIT ****** I've thought about doing it another way: Each function is passed in a reference to the MDB2 object as an argument instead of relying on the one that is *suposed to be* built in to the actual class it's self. Would this be better / more secure / more efficient?! Hello there
After a few years of spending less and less time coding, I've got a lot of catching up to do. Back when I left I usually would run without classes. Now this is a big deal for me today.
I do understand the concept of classes and already did some working models, mostly from my learning process.
Now here is what is bothering me:
<?PHP class database { // Variables public $test; // Constructor public function __construct() { $test = "4"; } // Functions // public function test() { var_dump($this->test); } } $test = new database; $test->test(); ?>Wether I run this script on itself, nor through another file, this does work. What i get is: NULL The constructor does run, I did an echo inside it. Also it does not matter if the variable is public, private or protected - it will be always NULL. Error_reporting is on E_ALL, does not show any errors. What have I overlooked? I'm looking for some clarification here from different viewpoints to understand real world applications. In a previous thread, I suggested to someone that they read up on singleton methods to restrict class duplication (oops!), I was quickly (and rightfully) shot down. I did this after having read through blog posts that also suggested singleton design to stop multiple MySQL connections. At the time I didn't consider that could be useful to some people.. fair enough. Thankfully I don't use singleton methods within my own code, but I do use static methods for most things. Reading through numerous blog posts, tutorials, etc.., it seems like static methods can also be considered anti-design and is something to avoid. So now it seems I'm at a point where I need to rewrite my existing framework & CMS, probably using dependency injection within my classes. I understand how this works, and why it makes sense. What I'm struggling with is understanding how to use dependency injection within a (personal) CMS application. For example - I have a config.ini file I have a class that reads the .ini file, stores the variables, and provides me methods to access them I have a content class that selects the relevant page/component from the DB (db & config dependency), then displays it via my template engine. Within the included view files I call component classes (articles, contact, etc..), each of these require a connection to the DB, which has a config dependency. Here's some code to explain it better - index.php <?php $settings = '/config/config.ini'; $config = new Config($settings); $db = new Database($config); $content = new Content( $db ); // Config may also be passed for content config - keeping it simple for example print $content->loadPage($_GET['page']); // This would now include the code below ?>Let's say that this then loads the article index (through $content->loadPage()). The view would look something like this - article_index.php <?php // Duplicated code $settings = '/config/config.ini'; $config = new Config($settings); $db = new Database($config); // Article code $articles = new Articles_Model($db); return $articles->getArticles(0,15); ?>Now my problem is that I'm duplicating the config and db class calls for no reason. Is the sollution to store these within a registry class? But then I'm creating globals, which again seems anti-design. Or is the problem how I load the active page? Any insights would be much appreciated. If a class has a constructor but also has a static method, if I call the static method does the constructor run so that I can use an output from the constructor in my static method? --Kenoli Guys thanks for helping me solve the problem i had but now i have another problem and i am lost. i have included the code below for you to have overview.
This is the code:
<table style="width:100%; margin-left:auto; margin-right:auto"> I have having a problem getting a mysql query to work. If I just use mysql_query it looks like this and works fine: INSERT INTO schedule (schedule_pk, schedule_month, schedule_day, schedule_year, schedule_hour, schedule_minute, schedule_type, employeenumber) VALUES ( NULL, 10, 10, 1999, 12, 6, 'DayIn', 3); If I put it through mysql_real_escape_string it turns it to this and does not work when I put it into mysql_query: INSERT INTO schedule (schedule_pk, schedule_month, schedule_day, schedule_year, schedule_hour, schedule_minute, schedule_type, employeenumber) VALUES ( NULL, 10, 10, 1999, 12, 6, \'DayIn\', 3); aka: $query = "INSERT INTO...." mysql_query($query); that works, but: $query = "INSERT INTO...." $sqlQuery = mysql_real_escape_string($query, $con); mysql_query($sqlQuery); results in the error. mysql_query($query); The error is: 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 '\'DayIn\', 3)' at line 1 Okey so i made a table that you put your name,author,and message when you submit it , it echoes a table with the name,author and message written (and it also echoes a delete buttom,so delete this post oif necessary) im new to php and i have been with this problem for a couple of weeks so i guess its time to ask for some help the problem is that i dunnot know how to make my delete buttom work! i tried if statement but it dosent work i also tried ternary operation and dint work :S i read that there is something like $post[ID](and this is supposed to get the ID of the post submmited, and delete it) im not sure, im so confused! help! XD this is the code <?php $tittle=$_POST['tittle']; $author=$_POST['author']; $message=$_POST['message']; if ($_POST['submitnews']){ $currentdate= date("y-m-d"); $currenttime=date("H:i:s",strtotime("-6 hours")); $post=mysql_query("INSERT INTO news VALUES('','$tittle','$author','$message','$currentdate','$currenttime')"); echo"Posted!"; } $select=mysql_query("SELECT * FROM news ORDER BY id DESC"); while ($row= mysql_fetch_assoc($select)) { $id=$row['id']; $tittle=$row['tittle']; $author=$row['author']; $message=$row['message']; $date=$row['date']; $time=$row['time']; if ($_SESSION['admin']) { echo " <table width='488px' id='news_table'> <tr> <td> </td> <td> <center><font size='5'>$tittle</font></center><br> </td> </tr> <tr> <td> </td> <td> $message </td> </tr> <tr> <td> </td> <td> <font size='1'>Posted By:<font color='green'>$author</font> on <font color='gray'>$date</font> at <font color='gray'>$time</font></font> <input name='delete' type='submit' value='delete'> <td> </td> </tr><br><br> </table>"; Hows it going guys. I am currently having a problem. I had a program that worked. I migrated the website and now the program is broken. Any time i try to run it, i get this error: Quote Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /home/thegoo20/public_html/class/wordgame/wordgame.php on line 31 Here is the code at that point: Code: [Select] function changeword(){ $result = mysql_query("Select words from CurrentWords"); $totalwords = array(); while ($row = mysql_fetch_array($result)){ $totalwords[] = $row["words"]; } $_SESSION['word'] = $totalwords[rand(0, count($totalwords)-1)]; $_SESSION['scrambled'] = str_shuffle($_SESSION['word']); } where line 31 is the while statement. Any help would be appreciated. Thanks I do not receive email for my published php file which is: <?php ///// easend.php ///// $youremail = "acdelco40108@yahoo.com"; /*put the email address here, between quotes, the email address you want the message sent to*/ $to = $youremail; $email = $_POST['EMail']; $name2 = $_POST['Name']; $street2 = $_POST['Street']; $city2 = $_POST['City']; $state2 = $_POST['State']; $zip2 = $_POST['Zip']; $Phone = $_POST['Home_Phone']; $Cell = $_POST['Cell_Phone']; $education = $_POST['email1']; $comments = $_POST['email2'] ; $headers = "From:" . $email; $fields = array(); $fields{"Name"} = "Name"; $fields{"Street"} = "Street"; $fields{"City"} = "City"; $fields{"State"} = "State"; $fields{"Zip"} = "Zip"; $fields{"Home_Phone"} = "Home Phone"; $fields{"Cell_Phone"} = "Cell Phone"; $fields{"EMail"} = "Email"; $fields{"email1"} = "Education"; $fields{"email2"} = "Comments"; $subject = "We have received the following information from your employment application"; $body = "We have received the following information from your employment application:\n\n"; foreach($fields as $a => $b) { $body .= sprintf("%20s: %s\n",$b,$_POST[$a]); } mail ($to, $subject, $body, $headers); //send mail to owner #end create email vars $headers = "From:" . $to; mail ($email, $subject, $body, $headers); //send mail to user #end create email vars echo "<head><META HTTP-EQUIV=\"Refresh\" CONTENT=\"2; URL=ThankYou.html\"></head>"; ?> I am trying to save this an an xml document but am getting this error when I try to open the xml file "feed.xml" - "XML Parsing Error: no element found" $xml = '<rss version="2.0"> <channel> <title> RSS Feed</title> <link></link> <description>the best industry-lead opinions</description> <language>en-us</language> </channel> </rss>"; $xml2 = new DOMDocument('1.0'); $xml2->Load($xml); $xml2->save("feed.xml"); I am trying to understand PHP OOP and I have some code that is not working. here is the error code. Code: [Select] Parse error: parse error, expecting `T_FUNCTION' in C:\wamp\www\testing\armor_lib.php on line 11 And here is the armor_lib.php file: <?php class armor { // Head public $head; public $torso; public $pants; public $gloves; public $boots; // new stuff here class head extends armor { function __construct($head){ $this->set_head($head); } } // Torso class torso extends armor { function __construct($torso){ $this->set_torso($torso); } } // Pants class pants extends armor { function __construct($pants){ $this->set_pants($pants); } } // Gloves class gloves extends armor { function __construct($gloves){ $this->set_gloves($gloves); } } // Boots class boots extends armor { function __construct($boots){ $this->set_boots($boots); } } } ?> And here is the php in the armor.php file I have: <?php $head = new armor("Leather Helm"); $torso = new armor("Leather Shirt"); $pants = new armor("Leather Pants"); $gloves = new armor("Chain Mail Gloves"); $boots = new armor("Leather Boots"); echo "You are wearing: " . $head->get_head() . "on your Head"; echo "<br />"; echo "You are wearing: " . $torso->get_torso() . "on your Torso"; echo "<br />"; echo "You are wearing: " . $pants->get_pants() . "on your Legs"; echo "<br />"; echo "You are wearing: " . $gloves->get_gloves() . "on your Hands"; echo "<br />"; echo "You are wearing: " . $boots->get_boots() . "on your Feet"; ?> Any Help in understanding this will be much appreciated. Thanks. |