PHP - Why It Uses The Constructor?
class 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. Similar TutorialsHello 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. 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. 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. void __construct ([ mixed $args [, $... ]] ) What is the "void" in the above code? (It looks like Java?!) TomTees 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 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 |