PHP - Basic Class Questions
I'm looking for a php class tutorial that talks about some very basic things that don't seem to get talked about in begaining php class tutorials.
Such as declaring variables within a class and when you should do that. And within a class what is the difference between a pubic and private function? The function thing I can guess at: private functions are only available for use within the class, but public functions can be called from outside the class, yes? Just a guess. But also I am confused about when I should declare variables within a class. For example I recently saw: Code: [Select] class something { private $this, $that, $theOtherThing; public function someFunction { ... } } Isn't there some PHP Classes For Idiots that covers this stuff? Similar TutorialsOk, so I'm trying to develop/remake a web based browser game that I used to play back in 2006. I've got a fair amount set up, considering I knew nothing about php/mysql about a week ago. However, I've made a registration process, login system, and the game pages (member only). However, I was talking to some people the other day, and I'm using MD5 to encrypt the passwords. The suggestion given to me was to use SHA2 with Salt. The problem that I'm facing is that no matter what I try, I can't seem to get the system working.. I've followed the advice originally recieved: no success. I've followed a tutorial online: no success. SO, I was wondering if someone from here could help me. My database has the extra 'salt' field setup.. and here's my uneddited working MD5 code: Code: [Select] <?php //Start session session_start(); //Include database connection details require_once('config.php'); //Array to store validation errors $errmsg_arr = array(); //Validation error flag $errflag = false; //Connect to mysql server $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD); if(!$link) { die('Failed to connect to server: ' . mysql_error()); } //Select database $db = mysql_select_db(DB_DATABASE); if(!$db) { die("Unable to select database"); } //Function to sanitize values received from the form. Prevents SQL injection function clean($str) { $str = @trim($str); if(get_magic_quotes_gpc()) { $str = stripslashes($str); } return mysql_real_escape_string($str); } //Sanitize the POST values $email = clean($_POST['email']); $login = clean($_POST['login']); $password = clean($_POST['password']); $cpassword = clean($_POST['cpassword']); $empire_name = clean($_POST['empire_name']); $race = clean($_POST['race']); $referrer = clean($_POST['referrer']); //Input Validations if($email == '') { $errmsg_arr[] = 'Email missing'; $errflag = true; } if($login == '') { $errmsg_arr[] = 'Username missing'; $errflag = true; } if($password == '') { $errmsg_arr[] = 'Password missing'; $errflag = true; } if($cpassword == '') { $errmsg_arr[] = 'Confirm password missing'; $errflag = true; } if( strcmp($password, $cpassword) != 0 ) { $errmsg_arr[] = 'Passwords do not match'; $errflag = true; } if($empire_name == '') { $errmsg_arr[] = 'Empire Name missing'; $errflag = true; } if($race == '') { $errmsg_arr[] = 'Race not selected'; $errflag = true; } if(strlen($login) > 20) { $errmsg_arr[] = 'Username exceeds allowed charachter limit'; $errflag = true; } if(strlen($empire_name) > 20) { $errmsg_arr[] = 'Empire Name exceeds allowed charachter limit'; $errflag = true; } //Check for duplicate login ID if($login != '') { $qry = "SELECT * FROM members WHERE login='$login'"; $result = mysql_query($qry); } if($result) { if(mysql_num_rows($result) > 0) { $errmsg_arr[] = 'Username already in use'; $errflag = true; } @mysql_free_result($result); } else { die("Query failed"); } //Check for duplicate Empire Name if($empire_name != '') { $qry = "SELECT * FROM members WHERE empire_name='$empire_name'"; $result = mysql_query($qry); } if($result) { if(mysql_num_rows($result) > 0) { $errmsg_arr[] = 'Empire Name already in use'; $errflag = true; } @mysql_free_result($result); } else { die("Query failed"); } //If there are input validations, redirect back to the registration form if($errflag) { $_SESSION['ERRMSG_ARR'] = $errmsg_arr; session_write_close(); header("location:register-form.php"); exit(); } //Create INSERT query $qry = "INSERT INTO members(email, login, passwd, empire_name, race, referrer) VALUES('$email','$login','".md5($_POST['password'])."','$empire_name','$race','$referrer')"; $result = @mysql_query($qry); //Check whether the query was successful or not if($result) { header("location: register-success.php"); exit(); }else { die("Query failed"); } ?> My second question is: I've got a set of permissions in my members database.. These are guest, player, mod and admin. I'm currently running my updates page by calling the updates from the database... How would i go about adding a link to the first page you come to (after logging in) that can only be seen by members who are in the admin permission? Because I'd like to make an admincp with a page to submit a form to the database that updates the updates page.. However, I'd rather the link to it only showed up for me and was invisible to other members.. Again, I'm only asking because I cant seem to find any information online at any tutorials or worksheets that I've come across.. And believe me, I've been searching quite a bit.. :/ Any help would be very much appreciated.. Cheers, /zythion/ 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 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 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 How does one go about using one class inside another? For example, building a class that does some series of functions, and uses a db abstraction layer class in the process? I do know how to do this but I am curious about whether or not there is a "preferred" way to do this. I know there are a couple ways to use a class (I'll call Alpha_Class) within another class (I'll class Beta_Class) Let's say we have this simple class (Beta_Class): class beta { function foo(){ } } If I wanted to use the Alpha Class within the Beta Class, I could any number of things. For example: class beta { function foo(){ $this->alpha = new alpha; //$this->alpha->bar(); } } Or you could simply use the $GLOBALS array to store instantiated objects in: $GLOBALS['alpha'] = new alpha; class beta { function foo(){ //GLOBALS['alpha']->bar(); } } You could even declare Alpha_Class as a static class and thus would not need to be instantiated: static class alpha { static function bar(){} } class beta { function foo(){ //alpha::bar(); } } Those are the only ways I can think of right now. Are there any other ways to accomplish this? I was wondering which way is the best in terms of readability and maintainability. 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>"; } } }} Hi all, I have two classes. Registration and Connection. Inside a registration.php I include my header.php, which then includes my connection.php... So all the classes should be declared when the page is loaded. This is my code: registration.php: <?php include ('assets/header.php'); ?> <?php class registration{ public $fields = array("username", "email", "password"); public $data = array(); public $table = "users"; public $dateTime = ""; public $datePos = 0; public $dateEntryName = "date"; function timeStamp(){ return($this->dateTime = date("Y-m-d H:i:s")); } function insertRow($data, $table){ foreach($this->fields as $key => $value){ mysql_query("INSERT INTO graphs ($this->fields) VALUES ('$data[$key]')"); } mysql_close($connection->connect); } function validateFields(){ $connection = new connection(); $connection->connect(); foreach($this->fields as $key => $value){ array_push($this->data, $_POST[$this->fields[$key]]); } $this->dateTime = $this->timeStamp(); array_unshift($this->data, $this->dateTime); array_unshift($this->fields, $this->dateEntryName); foreach($this->data as $value){ echo "$value"; } $this->insertRow($this->data, $this->table); } } $registration = new registration(); $registration->validateFields(); ?> <?php include ('assets/footer.php'); ?> At this point I cannot find my connection class defined on another included/included page. $connection = new connection(); $connection->connect; config.php (included within header.php) <? class connection{ public $dbname = '**'; public $dbHost = '**'; public $dbUser = '**'; public $dbPass = '**'; public $connect; function connect(){ $this->connect = mysql_connect($this->dbHost, $this->dbUser, $this->dbPass) or die ('Error connecting to mysql'); mysql_select_db($this->dbname, $this->connect); } } ?> Any ideas how to call it properly? Well the title may seem a bit confusing, but heres an example: Code: [Select] <?php class User{ public $uid; public $username; protected $password; protected $email; public $usergroup; public $profile; public function __construct($id){ // constructor code inside } public function getemail(){ return $this->email; } public function getusergroup(){ return $this->usergroup; } public function getprofile(){ $this->profile = new UserProfile($this->uid); } } class UserProfile(){ protected $avatar; protected $bio; protected $gender; protected $favcolor; public function __construct($id){ // constructor code inside } public function formatavatar(){ // avatar formatting code inside } public function formatusername(){ // format username? } } ?> As you can see, the User class(an outer class) has a property called Profile, which can be instantiated as a UserProfile object(an inner class). The two objects have distinct functionalities, but there are times when the UserProfile object needs to access property and methods from the user object. I know its easy for outer class to access methods from inner class by using the single arrow access operator twice, but how about the other way around? Lets say from the above example the userprofile can format the username displayed to the screen by adding a sun to the left of the username if the usergroup is admin, a moon if the usergroup is mod, and nothing if its just a member. The usergroup property is stored in the outer class, and can be accessed with this $user->getusergroup() method only. I know I can always do the hard way by passing a user object to the method's argument, but is there an easier way for the inner class UserProfile to access properties/methods for outerclass User? If so, how can I achieve that? Hello everyone, I have been doing web developing for a little while and just recently decided to make the leap to developing standalone applications. I started learning C++ and JAVA for this purpose, but quickly learned that PHP can also be used to this end, and since I am quite familiar with PHP, I thought it would make sense to start with PHP GTK. But before I jump right in, I have a few questions that I would greatly appreciate some answers for: Does PHP have any significant advantages/disadvantages over lower level languages such as C++ ? I would imagine that PHP being originally designed for web programming would be less suited for stand alones. I'm a little confused as to whether the GTK is a graphical user interphase software, the likes of QT and Netbeans, or is it a markup language like HTML, where the widgets are generated with text commands? Please I need a little clarification on that. Also are there any other tools that need to be downloaded to get started besides the GTK? Finally, am I supposed to learn OOP PHP to get going or is traditional procedural PHP sufficient? Answers to any or all of the above questions and any other advice would be highly appreciated. Thanks. Hi. I'll like to ask few questions about PHP, as I think they are related to it.
I've came across some webpages, what I've spotted is that a webpage displays content but each "page" has different argument and there is no filename.
For example:
"http://www.website.com/?home" is home-like webpage, by changing "/?home" to "/?anotherpage" land me on some other webpage on their website and so on. My question is how is it done? Is it done from PHP?
Another question I wanted to ask is.. I went on InvisionPower.Board forum (such as this PHP Freaks ). How to force "folders" to be displayed as "files"?
For example:
"http://forums.phpfre...ks-on-facebook/" which links to a thread.
Thanks in advance
I've been coding PHP for some time and would consider myself to be at an intermediate level. I can write code to do what I need but it's probably not the best way to do it. I rarely see any code that I am not able to read, understand, or follow. I've created modifications for everything from vBulletin, WordPress, Kayako Support Suit, Magento, and more. However, I've never really built a strong understanding around OOP. For example, let say you have the following classes: _main - db - admin - - modules - - - dashboard How would you share the db connection with the dashboard class? I've been trying to read up on Dependency Injections and Singletons but I haven't found an article that has explained it on a level that I can understand. I get a feeling that most people who use OOP in PHP have a background in Java or C++ and are much more familiar with everything. Could someone please explain this to me in simple terms or link me to an extremely well explained article that I'd be able to understand without a background in computer science? Thanks Howdy, I am new to SEO. Could you please help me? 1. I like to post programming tutorials to both my website & various programming forums. Is that going to screw up my website's ranking in Google? 2. My editor of my history website who sometimes posts essays there also posts them in some history forums. Is that bad for SEO? 3. I made a Facebook page for my history website. It says there "Promote your page" basically you pay $5 for around 100 likes. Has anyone tried that? Does it work? Because $5 seems like little money for additional 100 likes which will increase the traffic considerably. Thank you so much for the help! Hello, I'm fairly new to PHP, and I'm looking to create an online catalog for a furniture/appliance store. I'm wondering the best way to go about this. I'm looking at SQLMaestro's "PHP Generator for MySQL" http://www.sqlmaestro.com/products/mysql/phpgenerator/ ... But, I'm curious if you guys can point me in the right direction. I've never created a database before, and I want to do it the way that makes the most sense... Any advice would be appreciated!! |