PHP - Help With Using Class And Constructor
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. Similar TutorialsIf 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 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 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? 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. 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. 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 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! 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. I have mysqli object in Database class base: [color=]database class:[/color] class Database { private $dbLink = null; public function __construct() { if (is_null($this->dbLink)) { // load db information to connect $init_array = parse_ini_file("../init.ini.inc", true); $this->dbLink = new mysqli($init_array['database']['host'], $init_array['database']['usr'], $init_array['database']['pwd'], $init_array['database']['db']); if (mysqli_connect_errno()) { $this->dbLink = null; } } } public function __destruct() { $this->dbLink->close(); } } Class derived is Articles where I use object dBLink in base (or parent) class and I can't access to mysqli methods (dbLink member of base class): Articles class: require_once ('./includes/db.inc'); class Articles extends Database{ private $id, .... .... $visible = null; public function __construct() { // Set date as 2009-07-08 07:35:00 $this->lastUpdDate = date('Y-m-d H:i:s'); $this->creationDate = date('Y-m-d H:i:s'); } // Setter .... .... // Getter .... .... public function getArticlesByPosition($numArticles) { if ($result = $this->dbLink->query('SELECT * FROM articles ORDER BY position LIMIT '.$numArticles)) { $i = 0; while ($ret = $result->fetch_array(MYSQLI_ASSOC)) { $arts[$i] = $ret; } $result->close(); return $arts; } } } In my front page php I use article class: include_once('./includes/articles.inc'); $articlesObj = new articles(); $articles = $articlesObj->getArticlesByPosition(1); var_dump($articles); [color=]Error that go out is follow[/color] Notice: Undefined property: Articles::$dbLink in articles.inc on line 89 Fatal error: Call to a member function query() on a non-object in articles.inc on line 89 If I remove constructor on derived class Articles result don't change Please help me Ok. I know you can pass the object of a class as an argument. Example: class A { function test() { echo "This is TEST from class A"; } } class B { function __construct( $obj ) { $this->a = $obj; } function test() { $this->a->test(); } } Then you could do: $a = new A(); $b = new B($a); Ok so that's one way i know of. I also thought that you could make a method static, and do this: (assuming class A's test is 'static') class B { function test() { A::test(); } } But that is not working. I'd like to know all possible ways of accomplishing this. Any hints are appreciated. thanks Hi Can you call Class A's methods or properties from Class B's methods? Thanks. I have an existing instance of my class Database, now I want to call that instance in my Session class, how would I go about doing this? Hi, I need to be able to call a class based on variables. E.G. I would normally do: Code: [Select] $action = new pattern1() but i would like to be able to do it dynamicaly: Code: [Select] $patNum = 1; $action = new pattern.$patNum.() Im wondering if that's possible? If so what would the correct syntax be? Many Thanks. I have two classes: ## Admin.php <?php class Admin { public function __construct() { include("Config.php"); } /** * deletes a client * @returns true or false */ function deleteClient($id) { return mysql_query("DELETE FROM usernames WHERE id = '$id'"); } } ?> ## Projects.php <?php class Projects { public function __construct() { include("Config.php"); $this->admin = $admin; $this->dataFolder = $dataFolder; } /** * Deletes a project * @returns true or false */ function deleteProject($id) { $root = $_SERVER['DOCUMENT_ROOT']; $theDir = $root . $this->dataFolder; $sql = mysql_query("SELECT * FROM projectData WHERE proj_id = '$id'"); while ($row = mysql_fetch_array($sql)) { $mainFile = $row['path']; $thumb = $row['thumbnail']; if ($thumb != 'null') { unlink($theDir . "/" . substr($thumb,13)); } unlink($theDir . "/" . substr($mainFile,13)); } $delete = mysql_query("DELETE FROM projectData WHERE proj_id = '$id'"); $getDir = mysql_query("SELECT proj_path FROM projects WHERE id = '$id'"); $res = mysql_fetch_array($getDir); rmdir($theDir . "/" . $res['proj_path']); return mysql_query("DELETE FROM projects WHERE id = '$id'"); } } ?> How can I call deleteProject() from within Admin.php? Hi people! class FirstOne{ public function FunctionOne($FirstInput){ //do stuff and output value return $value1; } } Then:- class SecondOne{ public function FunctionTwo($AnotherInput){ //do stuff and output value return $value2; } } What I want to know is this, if I want to use FunctionOne() in Class SecondOne do I do it like this:- (Assume as I have instantiated the first class using $Test = new FirstOne(); ) class SecondOne{ function SecondedFunction(){ global $Test; return $Test->FunctionOne(); } public function FunctionTwo($AnotherInput){ //do stuff and output value return $value2; } public function FunctionThree(){ //some code here $this->Test->SecondedFunction();<--I think as I can omit the $this-> reference } } My point is: Do I have to do it this way or is there way of having this done through __construct() that would negate the need for a third party function? I have a version working, I just think that it is a little convoluted in the way as I have done it, so I thought I would ask you guys. Any help/advice is appreciated. Cheers Rw I have a class in which I have a function called connection. I am now trying to call this function from another class, but it will not work. It works if I put the code in from the other function rather than calling it but that defeats the purpous. class locationbox { function location() { $databaseconnect = new databaseconnect(); $databaseconnect -> connection();{ $result = mysql_query("SELECT * FROM locations"); while($row = mysql_fetch_array($result)) // line that now gets the error, mysql_fetch_array() expects parameter 1 to be resource, boolean given //in { echo "<option>" . $row['location'] . "</option>"; } } }} |