PHP - Calling Multiple Functions In Single Call From Class
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. Similar TutorialsI 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 All
I have not really played around with PHP in ages so I am having a hard time trying to figure out the best way to proceed. Anyhow... what I need to get done is to take a singleton pattern core database class that has a extended driver based class (ie; the type of database server the connection is connecting to), and build a new class that dynamically handles as many driver based connections that are called using a single instance. As a side note, I tried PDO but it only supports a single driver per class instance, and then each of those connections cannot not have their on set of properties that relate to each connection. Anyway, I was thinking that the best way to handle all the driver specific connections, is to hand out a 'unique hash reference' that points to an array of connection objects and the object properties. then when the client runs any sql function they pass the 'unique hash reference' which the class then returns the object and it properties that will be used by the class to call up the driver specific sql function that was requested by the client. So what do you all thing about that....
TIA stephanieT
PS...
I reason i need this is because I need to update up 25 different databases based on data stored on all the databases and not all of the database servers are of the same type, (ie; MSSQL, Oracle, MySQL, MariaDB, berkeley DB, postgres, sqlite2,3, etc, etc)! Edited January 16, 2019 by StephanieTOk. 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 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. 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. 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 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 ()? I have a user form with a dete button on a dropdown. When you click said button this runs function deleteUser(){ var e = event.target var uid = e.getAttribute("data-id"); console.log(e) console.log(uid) $.ajax({ type: 'post', data: {"ajax" : 'delUser', "id" : uid} }) } which goes into this if(isset($_POST['ajax'])){ switch($_POST['ajax']) { case 'newUserMod': exit(popNewUserModal()); break; case 'userMod': exit(popUserModal($_POST['id'])); break; case 'deleteUser': exit(deleteUser($_POST['id'])); break; } }; which calls this function in another file function deleteUser($id){ include 'includes/dbconn.php'; $stmt = $conn -> prepare("DELETE FROM user WHERE id = ?"); $stmt -> bind_param('i', $id); $stmt -> execute(); header('Location: manage-users'); } I know that i am getting the correct id in the ajax and i can see that the post happens correctly. Any ideas why the users are not being deleted? Hi I call a function with values of 51 and 100 but the function receives values 1 and 50
<?php // EmilyMoor Version 1.0.0 05-07-2019 Desmond O'Toole. ini_set('display_errors', 1); error_reporting(E_ALL); require("../secure/SecureFunctions.php"); require("secure/SecureFunctionsEmilyMoor.php"); $page = "Emily Moor"; session_start(); $Browser = $_SERVER['HTTP_USER_AGENT']; if (!isset($_SESSION["PageValue"])) $_SESSION["PageValue"] = '1'; $_SESSION["PageValue"] = 2; // Keeps going back to 1 if($_SESSION["PageValue"] == 1) { $_SESSION["StartValue"] = 1; $_SESSION["EndValue"] = 50; } if($_SESSION["PageValue"] == 2) { $_SESSION["StartValue"] = 51; $_SESSION["EndValue"] = 100; } if($_SESSION["PageValue"] == 3) { $_SESSION["StartValue"] = 101; $_SESSION["EndValue"] = 150; } if($_SESSION["PageValue"] == 4) { $_SESSION["StartValue"] = 151; $_SESSION["EndValue"] = 200; } if($_SESSION["PageValue"] == 5) { $_SESSION["StartValue"] = 201; $_SESSION["EndValue"] = 250; } if($_SESSION["PageValue"] == 6) { $_SESSION["StartValue"] = 251; $_SESSION["EndValue"] = 300; } echo $_SESSION["PageValue"] . " - " . $_SESSION["StartValue"] . " - " . $_SESSION["EndValue"] . "<br>"; $qStationDetails = GetChanelInfo($_SESSION["StartValue"],$_SESSION["EndValue"]); $rs = mysql_fetch_array($qStationDetails) or die ("E3001-101A"); $Name = $rs['Description']; ?> function GetChanelInfo($StartCH, $EndCH) // E2004 { echo "Channels = " . $StartCH . " " . $EndCH . "<br>"; // values are 1 and 50 $sqlChanelInfo = "SELECT * FROM TV_EmilyMoor WHERE ID >= $StartCH and ID <= $EndCH"; echo $sqlChanelInfo . "<br />"; $qChanelInfo = mysql_query($sqlChanelInfo) or die ("E3004-01A"); return $qChanelInfo; }
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 guys I AM NEW TO PHP AND MYSQLI... TRYING TO CALL FUNCTION BUT I GOT ERROR CANT FIGURE OUT WITH IT IS, THANKS FOR HELP ME functions.php
<?php
echo mysqli_error($db);
<?php
<?php ERROR Parse error: syntax error, unexpected ';', expecting '{' in C:\wamp64\www\gloria-blog\index.php on line 9
THANKS
Hi All I am wanting to start writing neater coding so am wanting to refer to coding in a functions file. So for example, If i was getting info from database using the following code Code: [Select] $queryone = "SELECT * from affiliate where size='300x250' ORDER BY RAND() LIMIT 1"; $result = mysql_query($queryone); while ($row = mysql_fetch_assoc($result)) { echo "".$row['code'].""; } I would want this to go in a file called functions.php Then in my index.php(for example) I would want to link up to this code. Can anyone point me in the right direction please? Thanks! Hello guys is it possible to create a single php file to contain all the functions to be called via AJAX and get AJAX to call the specific function required rather than having to create individual pages for each AJAX request you need to make? Many Thanks This is probably a quick one. I am pretty new to OOP, in fact somewhat a novice. I am working a lot more with objects lately as my previous "flat" php experience doesn't allow me to create clean and expandable applications. Of course though, questions will always pop up (that's what you guys are for?) One concept I am having trouble understanding, is the method to call a class. What is the difference between?: Code: [Select] <?php $cat = new class(); ?> and just simply: Code: [Select] <?php new class(); ?> Both appear to have the same output from my small amount of practice, but the first way seems strange to me. Being that I am very new to OO PHP, the first way looks like it is just defining a var. But in reality it is calling the class and running it? This seems very backwards to me and I am having a hell of a time understanding it. I am aware that the first way seems to be the "proper" way, but just can't fathom it. Could someone explain this to me a little further? thanks much, I have a PHP config file called config.php. inside the file is simular to this: Quote <?php class JConfig { var $offline = '0'; var $editor = 'tinymce'; var $list_limit = '20'; } ?> From another file, i have included config.php, but how do I call $editor to get "tinymce"? Thanks can someone help me I am trying to call a class function using a varible.... example say i go to index.php?page=contact i want to pull that class with out doing a switch statement can someone help me Code: [Select] <?php $Site = page; $Site->getPage($_GET['page']); ?> Code: [Select] <?php class page extends site { function getPage($page) { return $this->$page; } function Contact() { echo '<h2>Contact test</h2>'; echo '<form> </form>'; } } ?> I am calling an object from another class in the constructor of first class but when I call it in another function it does not access it's object. Here is the code. Code: [Select] <?php /* This is controller.php used to control the flow of data between view.php and model.php. This file cotains all the controlling mechanism of the data It was created on 11th Feb 2011 By Narjis Fatima for an Open Source Project and contains all the includes to the database etc. */ include ("view.php"); include ("functions.php"); $name = stripslashes($_GET['username']); $email = stripslashes($_GET['email']); //echo "in controller.php"; check_validate_input($name, $email); $newUser = new controller($name, $email); $action=$_GET['t']; $newUser->display_view($action); class controller { public $my_model; //is an object of model class public $user_info;//=array('id' , 'username' ,'role','email','interests','location', 'homepage'); function __construct($name,$email) { $my_model = new model(); $user_info = $my_model->check_members($name,$email); echo "<pre>"; print_r ($user_info); } function __destruct() { } function display_view($token) { echo "In display function"; echo "<pre>"; print_r ($user_info); if ($this->user_info == NULL) { if (($token=="register")) { show_registration_form(); } else{ show_mailing_form(); } } if ($this->user_info['role'] == "admin") { $myView = new view(); $myView->view_admin_menu(); } if ($this->user_info['role'] == "user") { $myView = new view(); $myView->view_user_menu() ; } }//close of function display_view() } /* name and email cominfg from index.php would be checked by the controoler class to be checked if it a vaild name and email. The database would be connected n the model.php*/ ?> The code for model.php is as follows Code: [Select] <?php //This is model.php created on 10th Feb 2011 .It deals with daytabase connection // //By NArjis Fatima //For the project of EDUForge an Open Source Software //include ("register.php"); class model{ public $dbh; public $user_arr=array('username','password','email','location','interest','homepage'); //cunstructor of model class //function to connect to database function __construct(){ try{ $this->dbh = new PDO("mysql:host=localhost;dbname=phpfaqproject",'root',''); //echo "connected"; } catch(PDOException $e){ echo $e-> getMessage(); } } public function check_members($username,$email) { //get_connected(); $sql = "SELECT * FROM account WHERE (username='" .$username ."' AND email='" .$email."')"; $sth = $this->dbh->prepare($sql); $sth->execute(); $result = $sth->fetch(); /* echo('<pre>'); print_r($result);*/ return ($result); } public function insert_data($user_info) { //$user_info = $user_in; //$dbh; try{ $dbh = new PDO("mysql:host=localhost;dbname=phpfaqproject",'root',''); //echo "connected"; } catch(PDOException $e){ echo $e-> getMessage(); } $dbh->exec("INSERT INTO account (username, userpassword, email, role, location, interest, homepage) VALUES ('" .$user_info['username']."','".$user_info['password'] ."','".$user_info['email']."', 'user','".$user_info['location']."','".$user_info['interests'] ."','".$user_info['homepage']."')"); } } ?> Please somebody help me. I am really stuck. I am also sending my attachment. Hi How do I turn this: Code: [Select] if($LCname=='Business_solutions'){ $newChild = Business_solutions::find_by_id(1); } In to something like this: Code: [Select] $newChild = $LCname::find_by_id(1); I'm calling lots of class's, and want to make it more dynamic. The 2nd example would be perfect, but that does not work. Is there an alternative? Thanks 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 |