PHP - Question On Classes->functions
Hi everyone,
Until now i didnt use classes and functions for sql related actions and now i would like to start. I started out with this : class.php --------------------------------------------------- class db { public function connect($database,$user,$password) { $db = mysql_connect("localhost",$user,$password) or die (mysql_error()); mysql_select_db($database); } static function fetch() { function getresults($query) { $resultArray = array(); $fetch = mysql_query($query) or die (mysql_error()); while ($row = mysql_fetch_assoc($fetch)){ $resultArray[] = $row; } return $resultArray; mysql_free_result($fetch); } } } and index.php ---------------------------- <?php require('class.php'); $connection = new db(); $connection->connect("testdb","root","root"); $connection->fetch()->getresults("SELECT * FROM users"); foreach (getresults() as $user) { echo "<div>{$user['user_first_name']}</div>"; } Similar TutorialsThis topic has been moved to Application Design. http://www.phpfreaks.com/forums/index.php?topic=314249.0 Hi, how do I use prepared statements when working with classes and functions? I need to do perform multiple identical inserts/updates to mySQL. I have been trying to implement into my connection class, based on what I have seen in examples I found on google. I keep getting fatal errors. My code is (save.php) <?php //Class extends DB_connect to access database class saveWorkout extends DB_Connect { // $stml->close(); public function get_jQueryData($planned_workout_id,$array_input) { // loop through workout progress, and check if input already exists in database for ($i = 0; $i < count($array_input['field_id']); $i++) { if(empty($array_input['field_id'][$i])) { $planned_workout_id = $array_input['planned_id'][$i]; $exercise_id = $array_input['exercise_id'][$i]; $set_id = $array_input['set_id'][$i]; $weight = $array_input['weight'][$i]; $reps = $array_input['reps'][$i]; $this->insertNewEntry->$stmt->execute(); } // closing else else { // Do something } //closing else } // Closing for statement } protected function insertNewEntry() { $stmt = $this->$connect()->prepare("INSERT INTO Workout_Log (planned_workout_id, exercise_id, set_id, weight, reps, entry_date) VALUES ( ?, ?, ?, ?, ?, ?)"); $stmt->bind_param($planned_workout_id, $exercise_id, $set_id, $weight, $reps, date("Y-m-d H:i:s")); } } // closing class save_workout ?> my connection file is looks like this (connect.php) class DB_Connect { private $servername; private $username; private $password; private $dbname; protected function connect() { $this->servername = "localhost"; $this->username = "root"; $this->password = "XXXXXX"; $this->dbname = "NNNNNNN"; $conn = new mysqli($this->servername,$this->username,$this->password,$this->dbname); return $conn; } }; Edited March 25, 2020 by Stoffer This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=345635.0 I've been wasting time reinventing the wheel with this one so I'd greatly appreciate if people here could share how they deal with this. So heres an example class:
class VarDataClass { private $module = 'show_vars'; public $category = 'DEFAULT CATEGORY'; public $title = 'DEFAULT TITLE'; public $option2 = 'DEFAULT VALUE'; public $show = 'SOMETHING'; public $output = 'box'; public $_settings = array( 'category' => 'DEFAULT CATEGORY', 'title' => 'DEFAULT TITLE', 'option2' => 'DEFAULT VALUE', 'show' => 'SOMETHING', 'output' => 'box' ); public function __constructor($options = array()) { } // some functions }So the $options parameter in the constructor contains all the custom settings for the class instance, lets say in this case they're all optional. Since they're all optional I made that $_settings array have default values. And for this example, I added another way I could do it, by adding the variables individually rather than as part of the settings array. So I'm wondering whats the best way to replace the default values with any values that the user happens to input. Is a list of variables easier, or is the $_settings array the way to go? I think the settings array would be the way to do it, so I'm thinking I should make some option setter function, but whats the easiest way to do that? Should I loop through every key in the settings array, and check if that key is present in the $options variable that the user input? Or is there some kind of array_replace function I can use that will set all the options in one go without having to use a loop? Another issue is its a pain in the ass for the user to input an associative array, its much easier to just to $object = new VarDataClass('CATEGORY','TITLE');etc. but then the problem is if they only want to set say the two last options, they'd have to do VarDataClass('','','','SHOW','OUTPUT');Basically I'm just looking for the most evolved way to handle these optional functions so I don't have to reinvent the wheel myself. Edited by entheologist, 29 August 2014 - 10:55 AM. I am working on my Pool class (base) and my FootballPool class (derived). I have this as my constructor Pool.php protected $pid, $uid, $pkid, $name; function __construct($pid, $uid){ $this->pid = $pid; $this->uid = $uid; $this->pkid = $this->pkid(); if(isset($_SESSION['picksInfo']['name'])) $this->name = $_SESSION['picksInfo']['name']; else $this->name = NULL; } Now a function in my FootballPool class needs to call $pid, $uid, and $pkid. How can I do that? I have tried this: Pool::$pid, but then I get this error Quote Fatal error: Access to undeclared static property: Pool::$pid in /var/www/core/includes/FootballPool.php on line 31 I am confused, because in the parents constructor, it is set. So basically, how can I call a variable set in the base class from a child or derived class? Currently I'm learning about objects and classes. I followed a tutorial about making a DB abstraction class (a mySQL select) and then I tried to adapt it and wrote a method to Insert a new name. However, then I had a problem: what if the value already exists in the DB? So I thought maybe I could write a method for that too, and hopefully this would be re-usable for other purposes. So I'm posting the code here and I hope someone could take a look at it, since I do not want to start any bad practices and start a habit of writing sloppy code. Would the code below be considered 'good code'? <?php // This file is called database.php class database { public $mysql; function __construct() { $this->mysql = new mysqli('localhost', 'root', 'password', 'db') or trigger_error('Database connection failed'); } /* Function to check whether value: $queriedName already exists inside table: $table and column: $column */ function findMatch($table, $column, $queriedName) { if ($result = $this->mysql->query("SELECT * FROM $table WHERE $column='$queriedName'")) { if (!$numberOfRows=$result->num_rows) { return false; } else { return true; } } } /* Function to select all records from table: $table */ function selectAll($table) { if ($result = $this->mysql->query("SELECT * FROM $table") ) { while($row=$result->fetch_object()) { $nameFields[]=$row->names; } return $nameFields; } } /* Function to insert a name: $newName into table: $table. Uses method finMatch to avoid doubles */ function insertName($table, $newName) { if ($this->findMatch($table, 'names', $newName)) { $result="Person already exists!"; return $result; } else { $result = $this->mysql->query("INSERT INTO $table(names) VALUES ('$newName')"); return $result; } // } } ?> Main page: // This file is called index.php require('database.php'); $newName='Mary Jane'; $result=$myDb->insertname('mytable', $newName); echo $result; This may sound like a very stupid question, but I can't find a clear answer anywhere. I'm making my first dive in OOP and all the tutorials only really show basic usage. They define a class, and show how to use it in a file. My question is how does it work to use an object throughout a program? Is it available everywhere or do I store things in sessions and start a new object on each page? For example: logging in a user. If I created an instance after confirming the credentials, would that same instance be available for use in say index.php, or would I just pass a session over and create a new instance on each page? Again, sorry if this seems dumb to some people. Hello, I'm new to the forum and I'm looking for advice. I use a bunch of classes in namespaces that are I'm attempting to organize for autoloading. In other words, a class called \Foo\Package\Class is loaded from the file at Foo\Package\Class.php. I'm using spl_autoload for this. (If I were on 5.2 I could be using underscore-delimited pseudo-namespaces just as well; the implementation detail isn't important) Now, I want to have multiple separate apps that use a single common library. Each app also has some classes that are local to it. How should I solve the autoloading problem? I thought of the following approach. Is it any good? Try autoloading from the common class library If it fails, try autoloading from the app's own local library Part 2 of the question: Within my apps, though, there are two types of classes: library ("vendor") classes that are only being used in that particular app so they don't need to be in the shared library, and app-specific classes that are the core of the app (so they, by definition, don't need to be in any shared library). I'd probably like to keep these two separate, so I'd need to add point #3 to the list above: search in the "core" class hierarchy of the local app. This gives 3 separate locations, and the problem is that they negate the advantages namespaces since there can be overlap. In which case one class will override the other during autoloading. So order of the above list would matter. And time would be wasted looking for a class in the first two places if it's more often in the third. A solution I was considering is sticking to just one central library of classes (and dumping all app-local libraries there). Then, the core classes that belong to one app would be under an \AppName namespace. I'm looking forward to some insights from the experts. How do you guys organize your class libraries? I'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. Can someone give me an actual time when functions would become handy? Thanks! Hi i have a function strored in a seperate file (included in my main php page for use), my question is a simple one but i cannot seem to find the answer on the web to this: I call the function as follows passing the variable $name <?php myfunction($name) ?> The function does somehting simple such as: <?php function myfunction ($name) { if ($name = 'bob') { return true; } else return false; } ?> How do i then obtain the true or false value of the function from back with my main php page? Hi there just wanted to ask you a general question regarding referenced variables and functions in PHP. I have this code: function theRefFunction(&$var){ $var = $var +1; return $var; } $a = 50; echo $thisvalue = theRefFunction($a); Just for learning purposes, as allot of times beginning PHP seriously developers who want to improve on memory consumption in PHP find this tricky, is there any point in using an example like this? I.e. would I really need the &$var as the parameter for the function called 'theRefFunction()'? Just wondered thats all, if not what would be a better way for really using it? It's just so I can go onto maybe doing a loop in it and setting it as a real example like working out tax and stuff like that, just for learning purposes, won't yet be using it. Just wanted to build up as I said earlier a library of things I have done and make maybe my own tutorial site. I look forward to any replies, Jeremy. I have asked this question in 3 different places but I get no answers lol. I hope to find some help here.
i want to only display user role for keymaster and moderator users.
I don't want every participant to have their role shown , only the keymaster and moderators are important enough to me to show their role next to their avatar. The following function code i found, and used... It worked but has some issues:
function role_show () { $displayed_user = bbp_get_reply_author_id() ; $role = bbp_get_user_role( $displayed_user); if ( bbp_is_user_keymaster($displayed_user) ||$role == 'bbp_moderator') $args['show_role'] = true ; else $args['show_role'] = false ; return $args ; } add_filter ('bbp_before_get_reply_author_link_parse_args', 'role_show' )Code Issues: On the Forums topic post lists, This code also removes the avatar from showing in the same cell section as the “last post by” . And it removes the “last post by” name in this same section. How can I fix this ? If needed, I could implement this code again and provide a link to the error so you can see. Thank you for any help. Side notes: Someone told me to try function role_show ($args) {As my first line , but it did not work. It resulted in the following screenshot : as Attached Files functions-picture.png 35.46KB 0 downloads 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? I have a script I am putting together that simulate a cricket game. The only issue is, that there are a huge number of functions because there doesn't seem to be any other way to do this properly. As well as this, there a while() loop and all this seems to be leading to the page reaching a max 30 second timeout when generating the result. My code is attached below, it is quite messy at the moment because i've just be working on it, but I was wondering if anyone has any solutions of how I can speed this up or change to prevent a timeout: <?php // Error reporting error_reporting(E_ALL); // Connect DB mysql_connect("wickettowicket.adminfuel.com", "rockinaway", "preetha6488") or die(mysql_error()); // Select DB mysql_select_db("wickettowicket") or die(mysql_error()); // MySQL queries to find batsmen and bowlers $array_batsmen = mysql_query('SELECT id, name, ability, strength FROM wtw_players WHERE team_id = 1 ORDER BY id ASC'); $array_bowlers = mysql_query('SELECT id, name, ability, strength FROM wtw_players WHERE team_id = 2'); // Start table for data $data = '<table width="600px">'; // Create blank scorecard while ($array_bat = mysql_fetch_array($array_batsmen)) { $data .= '<tr><td>'.$array_bat['name'].'</td><td></td><td></td><td>0</td></tr>'; } // Set up arrays for players $current_batsman = $current_bowler = array(); // Reset query mysql_data_seek($array_batsmen,0); $in_one = $in_two = $it = ''; function currentBatsman($id, $name, $ability, $strength, $out, $in, $runs) { global $current_batsman; $current_batsman = array ( 'id' => $id, 'name' => $name, 'ability' => $ability, 'strength' => $strength, 'out' => $out, 'in' => $in, 'runs' => $runs ); echo 'set current'; } // Set up arrays of batsmen while ($array = mysql_fetch_array($array_batsmen)) { if ($it < 3 && $in_one == '') { currentBatsman($array['id'], $array['name'], $array['ability'], $array['strength'], 0, 1, 0); $batsmen[$array['id']] = array ( 'id' => $array['id'], 'name' => $array['name'], 'ability' => $array['ability'], 'strength' => $array['strength'], 'out' => 0, 'in' => 1, 'runs' => 0 ); $in_one = $array['id']; $current = $array['id']; $it++; } else if ($it < 3 && $in_two == '') { $batsmen[$array['id']] = array ( 'id' => $array['id'], 'name' => $array['name'], 'ability' => $array['ability'], 'strength' => $array['strength'], 'out' => 0, 'in' => 1, 'runs' => 0 ); $in_two = $array['id']; $it++; } else { $batsmen[$array['id']] = array ( 'id' => $array['id'], 'name' => $array['name'], 'ability' => $array['ability'], 'strength' => $array['strength'], 'out' => 0, 'in' => 0, 'runs' => 0 ); } } // Bowler Array while ($array = mysql_fetch_array($array_bowlers)) { $bowlers[] = array ( 'name' => $array['name'], 'ability' => $array['ability'], 'strength' => $array['strength'] ); } // Reset both queries mysql_data_seek($array_bowlers,0); mysql_data_seek($array_batsmen,0); function changeBatsman($just_out) { global $array_batsmen, $batsmen; //Update array $batsmen[$just_out] = array ( 'in' => 1, 'out' => 1 ); while ($array = mysql_fetch_array($array_batsmen)) { if ($just_out != $array['id'] && $batsmen[$array['id']]['out'] != 0) currentBatsman($array['id'], $array['name'], $array['ability'], $array['strength'], 0, 1, 0); } // Reset query mysql_data_seek($array_batsmen,0); echo 'change batsman'; } function swapBatsman($other_batsman) { global $array_batsmen, $batsman; while ($array = mysql_fetch_array($array_batsmen)) { if ($other_batsman != $array['id'] && $batsman[$array['id']]['out'] != 0 && $batsman[$array['id']]['in'] == 1) currentBatsman($array['id'], $array['name'], $array['ability'], $array['strength'], 0, 1, 0); } // Reset query mysql_data_seek($array_batsmen,0); echo 'swap batsman'; } $runs = $outs = $balls = $overs = 0; $played = array(); function selectBowler() { global $bowlers, $current_bowler; // Select random bowler $choose_bowler = array_rand($bowlers, 1); $current_bowler = array ( 'name' => $bowlers[$choose_bowler]['name'], 'ability' => $bowlers[$choose_bowler]['ability'], 'strength' => $bowlers[$choose_bowler]['strength'] ); } /* function selectBatsman(); { global $array_batsmen; while ($array_batsmen[]['out'] != 1) { }*/ function bowl() { global $batsmen, $bowlers, $current_bowler, $current_batsman, $data, $balls, $outs, $runs; if ($current_batsman['out'] == 0) { echo 'bowling'; // Set the initial number $number = rand(0, 190); // Ability of batsman if ($current_batsman['ability'] > 90) $number += 30; else if ($current_batsman['ability'] > 70) $number += 15; else if ($current_batsman['ability'] > 50) $number += 2; else $number = $number; // Strength of batsman if ($current_batsman['strength'] > 90) $number += 15; else if ($current_batsman['strength'] > 70) $number += 10; else if ($current_batsman['strength'] > 50) $number += 5; else $number = $number; // Depending on overs if ($balls > 270) $number += 30; else if ($balls > 120) $number -= 10; // Ability if ($current_bowler['ability'] > 90) $number -= 30; else if ($current_bowler['ability'] > 70) $number -= 15; else if ($current_bowler['ability'] > 50) $number -= 2; else $number = $number; // If batsman has made a huge total of runs, we need to knock some numbers off - more likely to get out if ($current_batsman['runs'] > 200) $number -= 70; else if ($current_batsman['runs'] > 100) $number -= 30; // Finally sort out runs if ($number > 190) $run = 6; else if ($number > 170) $run = 4; else if ($number > 160) $run = 3; else if ($number > 100) $run = 2; else if ($number > 50) $run = 1; else if ($number > 10) $run = 0; else if ($balls > 120 && $number > 0) $run = 0; else $run = -1; // Increase number of balls $balls += 1; // Are they out? if ($run == -1) { $current_batsman['out'] = 1; $played[] = $current_batsman['id']; $find = '<tr><td>'.$current_batsman['name'].'</td><td></td><td></td><td>0</td></tr>'; $replace = '<tr><td>'.$current_batsman['name'].'</td><td></td><td>'.$current_bowler['name'].'</td><td>'.$current_batsman['runs'].'</td></tr>'; $data = str_replace($find, $replace, $data); changeBatsman($current_batsman['id']); echo 'out'; } else { $current_batsman['runs'] += $run; $runs += $run; if ($run == 1 || $run == 3) { swapBatsman($current_batsman['id']); echo 'time to swap'; } echo $run; } // Count outs if ($current_batsman['out'] == 1) $outs += 1; } } function game() { global $main, $batsmen, $bowlers, $data, $batted, $balls, $outs, $current_batsman; // Check if possible while ($balls <= 295 && $outs < 10) { selectBowler(); // Actually bowl now bowl(); } } game(); echo $data; I teaching myself php, but I am coming from java and other compiled languages, so the process has been a little bumpy. I am trying to do something like this: Code: [Select] class my_class { function one () { $two = two (); $three = three (); $five = $two + $three; return $five; } function two () { $two = 2; return $two; } function three () { $three = 3; return $three; } } Unfortunately, I keep getting an error message saying that my call to two () is an undefined function. I am gathering from this that the scope of one () is not aware of the existence of two (). Is there a way to get around this so I can call two () and three () from one ()? Hi there,
This might a newbie question but I need help understanding PHP classes which am currently learning.
I have an index page.
With this three included files.
database.php
config.php
account.php
on database.php, the class is declared using $connection new Database(...), on this page is also all the coding for this class.
In config.php is a declared class of $account new Account($user_id);
and on account.php is all the details for the account class.
on the index.php is echo $account->sayHello;
However, My page is throwing out an error because I'm trying to use $connection->query(..) in my account.php / Account class.
I have tried to extend the Account class with Database but still have no luck.
How can I make sure the I can use a class function from another page in my Account class?
Thanks for reading
Hi, I want to build a simple calculator class and one of the function is to calculate the factorial, but for some reason I cannot get this to work. Here is class: ========= Code: [Select] <?php class Calculator { function factorial($n) { if($n==1) return 1; else return factorial($n-1)*$n; } }//END CLASS Calculator $calculator=new Calculator(); print $calculator->factorial(3); ?> But it doesn't work, I know this is simple but I am a little rusty with object oriented programming. I'd appreciated any help! ini_set('display_errors', 1); error_reporting(E_ALL); class A { private function operation1() //only be used inside this class { echo 'operation1 called'; } protected function operation2() //only inside this class { echo 'operation2 called'; } public function operation3() //public can be used in any class { echo 'operation3 called'; } } class B extends A { function _construct() { //$this->operation1(); //$this ->operation2(); $this->operation3(); } } $b = new B; can someone please tell me why this code doesn't work ? |