PHP - How Can I Take Some Normal Php Functions And Put Them In To An Oop Class?
hello
i have some normal php functions that i want to put into a oop class. i cant seem to make the right changes to make it work. could some one help please. thanks these are the php functions Code: [Select] <?php function hasChild($parent_id) { $sql = "SELECT COUNT(*) as count FROM category WHERE parent_id = '" . $parent_id . "'"; $qry = mysql_query($sql); $rs = mysql_fetch_array($qry); return $rs['count']; } function CategoryTree($list,$parent,$append) { $list = '<li>'.$parent['name'].'</li>'; if (hasChild($parent['id'])) // check if the id has a child { $append++; $list .= "<ul class='child child".$append."'>"; $sql = "SELECT * FROM category WHERE parent_id = '" . $parent['id'] . "'"; $qry = mysql_query($sql); $child = mysql_fetch_array($qry); do{ $list .= CategoryTree($list,$child,$append); }while($child = mysql_fetch_array($qry)); $list .= "</ul>"; } return $list; } function CategoryList() { $list = ""; $sql = "SELECT * FROM category WHERE (parent_id = 0 OR parent_id IS NULL)"; $qry = mysql_query($sql); $parent = mysql_fetch_array($qry); $mainlist = "<ul class='parent'>"; do{ $mainlist .= CategoryTree($list,$parent,$append = 0); }while($parent = mysql_fetch_array($qry)); $list .= "</ul>"; return $mainlist; } ?> this is the class Code: [Select] <?PHP require_once(LIB_PATH.DS.'database.php'); class Menu extends DatabaseObject { protected static $table_name="menu"; protected static $db_fields = array( 'id', 'parent_id', 'name' ); public $id; public $parent_id; public $name; // "new" is a reserved word so we use "make"(or "build") public static function make( $id, $parent_id, $name) { if(!empty($id)) { $kw = new Menu(); $kw->id = (int)$id; $kw->parent_id = (int)$parent_id; $kw->name = $name; return $kw; }else{ return false; } } //end function make //PUT FUNCTIONS HERE...... function hasChild($parent_id) { $sql = "SELECT COUNT(*) as count FROM category WHERE parent_id = '" . $parent_id . "'"; $qry = mysql_query($sql); $rs = mysql_fetch_array($qry); return $rs['count']; } function CategoryTree($list,$parent,$append) { $list = '<li>'.$parent['name'].'</li>'; if (hasChild($parent['id'])) // check if the id has a child { $append++; $list .= "<ul class='child child".$append."'>"; $sql = "SELECT * FROM category WHERE parent_id = '" . $parent['id'] . "'"; $qry = mysql_query($sql); $child = mysql_fetch_array($qry); do{ $list .= CategoryTree($list,$child,$append); }while($child = mysql_fetch_array($qry)); $list .= "</ul>"; } return $list; } function CategoryList() { $list = ""; $sql = "SELECT * FROM category WHERE (parent_id = 0 OR parent_id IS NULL)"; $qry = mysql_query($sql); $parent = mysql_fetch_array($qry); $mainlist = "<ul class='parent'>"; do{ $mainlist .= CategoryTree($list,$parent,$append = 0); }while($parent = mysql_fetch_array($qry)); $list .= "</ul>"; return $mainlist; } ?> Similar TutorialsI think I need to use $this, but I need to be able to add the two values returned from both of my functions. How would I do that? Code: [Select] public function get_users_edge($uid) { $users_primary->get_users_primary_edge($uid); $users_dynamic->get_users_dynamic_edge($uid); echo $users_primary + $users_dynamic; } Hi! I have a class with many functions/methods. I want to split this into different files so I can easily edit and add functions. I want every functions to be able to call eachother and with that I mean, they have to be for example in same document. My question is: I can't have a class and include functions like this: Code: [Select] class DB { include('select_functions.php'); //Only includes function's no class include('insert_functions.php'); //Only includes function's no class include('delete_functions.php'); //Only includes function's no class function test() { } } The includes will output fatal errors... How can I solve this so I can have all functions in different files but still use ONE object to call them! Thanks! Hi,
I'm struggling to understand how to load a PHP classes for my database into a php function.
My class in on another file, which is included into my page.
I then have a function that usings the class of $database->query in the function, but for some reason this doesn't work.
However the class works on the page outside of the function, is there someway I must load the class into my function?
Thanks for reading.
I am currently building my own MVC Framework and I have run into an issue that I can't solve when attempting to use 2 methods from a single model. I know that this isn't an issue with the queries or information being return. I am unsure of the proper way that I can call 2 methods when checking to see if a user is logged in... The issue that I face is both methods are calling the DB and it throws a PDO error which I don't know how to get around the issue.. Any guidance would be nice as I have been banging my head over this issue. Thank you!
Fatal error: Uncaught Error: Call to undefined method PDO::Select() in C:\xampp\htdocs\PicWrist\app\models\user.class.php:318 Stack trace: #0 C:\xampp\htdocs\PicWrist\app\controllers\home.php(21): User->getUser('4') #1 C:\xampp\htdocs\PicWrist\app\core\app.php(36): Home->index() #2 C:\xampp\htdocs\PicWrist\app\init.php(47): App->__construct() #3 C:\xampp\htdocs\PicWrist\public\index.php(5): require('C:\\xampp\\htdocs...') #4 {main} thrown in C:\xampp\htdocs\PicWrist\app\models\user.class.php on line 318
//Controller <?php /** * Load the View */ class Controller{ public function view($view, $data = []) { if (file_exists('../app/views/' . $view . '.php')) { require_once '../app/views/' . $view . '.php'; } } public function model($model, $data = []) { if (file_exists('../app/models/' . $model . '.class.php')) { require_once '../app/models/' . $model . '.class.php'; return new $model(); } else return false; } } ?> //Home Controller <?php Class Home extends Controller { public static $user; public $errors; public function __construct() { self::$user = $this->model('user'); } public function index() { $userdata = []; $data = []; show(self::$user); $isLoggedin = self::$user->isLoggedin; show($isLoggedin); $userdata = self::$user->getUser($_SESSION['user_id']); show($userdata); $this->view('home', $data); } } ?> <?php /** * Users */ class User { private $db; private $errors = ''; public $isLoggedin = False; public $isAdmin = False; public function __construct() { $this->isLoggedIn(); } public function isLoggedIn() { if(isset($_SESSION['user_id'])){ $data['user_id'] = $_SESSION['user_id']; $db = Database::getInstance(); $query = "SELECT * FROM users WHERE user_id = :user_id LIMIT 1"; $results = $db->Select($query, $data); if (is_array($results)) { $this->isLoggedIn = True; } } } public function getUser($id) { if(isset($id)) { $data['user_id'] = intval($id); $db = Database::getInstance(); $query = 'SELECT * FROM users WHERE user_id = :user_id'; $results = $db->Select($query, $data); if (is_array($results)) { return $results; } else { return False; } } else { return False; } } //DB <?php /** * Database Connection */ class Database { private $dbHost = DB_HOST; private $dbUser = DB_USER; private $dbPass = DB_PASS; private $dbName = DB_NAME; private $statment; private static $dbHandler; private $error; public function __construct() { $conn = 'mysql:host=' . $this->dbHost . ';dbname=' . $this->dbName; $options = array( PDO::ATTR_PERSISTENT => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ); try { self::$dbHandler = new PDO($conn, $this->dbUser, $this->dbPass, $options); } catch (PDOException $e) { self::$error = $e->getMessage(); echo self::$error; } } public static function getInstance() { if(self::$dbHandler) { return self::$dbHandler; } return $instance = new Self(); } public function Select($query, $data = array()) { $statement = self::$dbHandler->prepare($query); $result = $statement->execute($data); If($result) { $data = $statement->fetchAll(PDO::FETCH_OBJ); if(is_array($data)) { // show($data); return $data; } } return False; } public function Update($query, $data = array()) { $statement = self::$dbHandler->prepare($query); $result = $statement->execute($data); If($result) { return True; } return False; } } ?> Edited July 14 by avargas94 Wrong Code Hi, I'm having a bit of a problem understanding why I'm not able to use the class I'm extending off of functions. I have a category class that extends off my core class, inside that category class, I'm able to use the core functions and variables inside all custom functions, but not the __construct function. So, to be clear, inside class class, I'm able to call $this->core->function() inside custom functions, such as function add_parent(), but not the __construct function. Why is this happening, what is the logic behind this? This is how I'm extending the class off of the core class: Code: [Select] <?php $core = new core; $parent = new parents; $parent->core =& $core; ?> With this, like I said, I'm able to use all of my core functions inside all other classes called this way, so inside all of the other classes I can do: Code: [Select] <?php $this->core->function(); ?>everywhere besides __construct(). Do I not have the class called properly? Do I need to pass my core class through differently? How can I fix this? Thanks. This is a bit of a more advanced question so I am hoping there are some advanced programmers online at this time . Anyways basically I want to be able to "queue" functions from a class in a single call and am wondering if I am doing it correctly or if there is a better way to do it. Here is my code: <?php class test { private static $one; private static $two; private static $three; public function callOne($val){ $one .= $val; return $this; } public function callTwo($val){ $two .= $val; return $this; } public function callThree($val){ $three .= $val; return $this; } public function print(){ echo $this->one.' '.$this->two.' '.$this->three; } } ?> now when I want to call this I can do: $test = new test(); $test->callOne('one')->callTwo('two')->callThree('three'); $test->callOne('another one'); $test->print(); Is there a better way to do this or is there a different method of doing this? Just wanna make sure I am doing it right lol. Was just wondering why some people choose NOT to make use of static functions when initializing objects via Factory Classes/Containers. What are the benefits of initializing the Factory class when for all intensive purposes, it's only used to initialize new classes, etc? Does this have any impact on Dependency Injection? I'm assuming that it doesn't since that would defeat the purpose. --------- Also, I've noticed that there seems to be an intense stigma within the development community in regard to singletons. Are singletons necessarily a bad thing? What about database objects? One argument I've heard is that this can often impact the flexibility of your application in the event that a new instance of said class needs to be initialized(a second completely separate connection). However, I was thinking that you could simply store these objects within a static member variable in the factory class; leaving the Database Class' __construct public in the event that you need to create that second/third/fourth connection. Wouldn't this resolve the issue? Hey guys im fairly new to php i cant really keep using that as an excuse anyway im to the point where i am comfortable with procedural php style programming and i have moved on to object orientated and prepared statements etc. Anyways this has no relevance to that sorry. Ok when using $_GET in php say for example i wanted to log a user out i would use ?status=logout or whatever i have started to instead use that use codes like ?abihcofscj=21904jkq i know this looks weird and there is probs no need but does any over sites use this type of behavior or am i just being retarded haha thanks Hi All, When I put echo memory_get_usage(); at the very beginning of a php file I get 51207808. Is this normal while there is not much processing to do ? This happens even for very small php files that only display html syntax. Thanks! I have a string in php: Quote Sat, 28 Apr 2012 05:09:45 GMT I want to convert it to timestamp Example: 1335594473 i have Created a Session with this code $_SESSION['USER_NAME'] = trim($_POST['username']) How can i access the $_SESSION['USER_NAME'] in other Pages ; and will this code for $var = $_SESSION[USER_NAME] can i get the SESSIOn value in " $var" variable ?? Hello,
Is anybody aware of a statistical function in PHP which returns the inverse of the normal cumulative distribution, given a probability, mean and standard deviation as inputs? Thank you. Hi, I am using PHP mail() function to sent message. Following is the code, the message is received in email account, but as attachment, not displayed in the body section as normal message would. Please can you guys help, as why is this message going as attachment, but not being displayed in the body of email. Below is the url which gives preview as to what I mean. http://i56.tinypic.com/29fujxf.jpg Code: [Select] $to = $_POST['to']; $subject = ' web visior'; $customer = stripslashes($_POST['customer']); $email = stripslashes($_POST['email']); $contactinfo = stripslashes($_POST['contactinfo']); $body = stripslashes($_POST['enquiry']); $header = 'From:'.$email.'\r\n'; $header = 'Reply-To:'.$email.'\r\n'; $header = 'X-Mailer: PHP/' . phpversion(); $header = 'Content-type: text/html\r\n'; $message = '<html><body> <table> <tr><td>From:'.$customer.'</td></tr> <tr><td>Email:'.$email.'</td></tr> <tr><td>Contact No'.$contactinfo.'</td></tr> <tr><td style="center"><b>Message:</b></td></tr> <tr><td>'.$body.'</td></tr> </body></html>'; Regards, Abhishek Hello all, I have a social network site that has users. Each user has a profile and a id. Myself and two other people are admins and are granted access to certain pages via $admin = true. I have recently hashed everyones passwords. I need to allow admins the ability to proxy a user or login as a different user or become another user for moderation purposes. via OOP there is a $auth->id which is the person's id who is logged in or their user id and $prof->id which is another persons id I am looking at. Meaning if I am looking at someones profile, it is their user id. I am trying to figure out a simple page to create where if $admin you can type a desired id in a input box, press enter and you are all of a sudden logged in as that id. Thanks in advance 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 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 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 Can you call Class A's methods or properties from Class B's methods? Thanks. 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 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 |