PHP - Static Class
I write for example class Text:
class Text { public static function test() { return 'test text'; } } Today I found this code: class Text { /** * Protected constructor since this is a static class. * * @access protected */ protected function __construct(){ // Nothing here } public static function test() { return 'test text'; } } How much appropriate is to write this? /** * Protected constructor since this is a static class. * * @access protected */ protected function __construct(){ // Nothing here } 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 Is it ok to do this? Code: [Select] class Two { function anything() { classOne::anyMethod(); } } I'm sure it is but this doesn't pose very well for if I wanted to swop out one class for another. I'd then have to make changes to the code (unless I were sure all classes were named the same). -- What I want it for (and this may be another issue), is this: I may need to create more than one database instance: Code: [Select] //Database exends mysqli $db[1] = new Database(2);//database 2 used this time $db[2] = new Database(5);//db5 I then always use Database::closeAll() at any point in my script to ensure all connections are closed. Of course $this->close wouldn't close all instances/connections, just the one I was working on. I know I don;t have to close all connections, but I may as well, and there are other occasions where the first part of this question applies, so please don't just respond "no need to close". Database::closeAll() is this: Code: [Select] public static function closeAll() { //closes ALL active instances (not just this one) global $db; foreach($db as $v) { $db[$v]->close(); unset($db[$v]); } } heres an example of the code i have Code: [Select] class someclass { public function run($parm) { system($parm); } public static function create($item1,$item2) { $this->run($item1 . $item2); } } then i have a file that attempts to use the create method: someclass::create($one,$two); when interpreting, i get this error: "Using $this when not in object context in" does anyone know how I can fix this? I think I understand why its wrong (the class hasn't really been set up) - I just dont know how to correct it. Is there a way I can access class functions without using $this ? additionally I tried making the run method static too, but that didnt seem to work. I have the following simple class: Code: [Select] class Settings { public static $mysql_datetime_format = "%c/%e/%Y %l:%i %p " . date("[T]"); } And referencing like: Code: [Select] echo Settings::$mysql_datetime_format; But, I am getting the error: Parse error: syntax error, unexpected '.', expecting ',' or ';'. Why is this invalid? I have 2 php files. I am unable to get B's global variable from A's static method: A.php Code: [Select] class c_A { public static function f_A() { include_once( "B.php" ) ; print f_B() ; } } c_A::f_A( ); // only prints "B : " B.php Code: [Select] $gvs = "global variable from B" ; function f_B() { return "B : " . $GLOBALS[ "gvs" ] ; } any thoughts? thanks, Shannon Hello, my first post here. I created a Validation class that depends entirely on static methods. It appears to be working well, but perhaps I misunderstood exactly the purpose and the consequences of using static methods. My class essentially looks like this: class Validate { static public $errors = array(); static public $valid = array(); static public function Name($name) { if ($name != '') { self::$valid['name'] = $name; return true; } else { self::$errors['name'] = 'Name is empty'; return false; } } } Does this create any chance whatsoever for a collision of data from multiple users? I am beginning to think it does, simply because from what I have recently learned about static methods, theyr'e essentially global variables because they are not instantiated. If that's the case, then it would seem possible that during times of heavy use, any application depending on this class would confuse submitted data. Any thoughts? Thanks in advance. Hi guys, I am trying something fairly simple but I'm not sure if this would be a good practice. Basically I am using a big class called CommonLibrary that holds common functions as methods and common variables as static variables. But I have some variables here and there like $allAlphabet = range ('a' , 'z'), that cannot be declared as a property because it gives me a parse error. I don't want to call an object for this class because instancing it is of no use. Values will never change with regards to instances. So the next best thing that I tried was declaring all static variables first, and then changing thei property values inside the class __construct with self::$variable = 'somevalue', and then using this code below to assign values to the empty static variables. $dummyObject = new CommonLibrary; unset($dummyObject); echo CommonLibrary::$staticVariable; // This property is NULL before the constructer is triggered. Anyone recommend any better ways of doing this? Thanks in advance! 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? I thought I was a beginner PHPer but now I'm not even sure I'm that. I have this class here which starts with: Code: [Select] private static $FormatType = ""; but then further down: Code: [Select] public function SetFormatType($NewFormatTypeId) { $this->FormatType = $NewFormatTypeId; } public function GetFormatType() { return $this->FormatType; } Do you suppose that the original developer just had a singleton or something, then latter on he found that he was making more instances and PHP tolerates this behavior? Or am I missing something? 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? Is it possible to have a static variable in php? I want the value of a variable to remain unchanged the next time a function is called.
We are able to access Static/Non-static methods with :: operator along with Class name. What for static in this case? I am using php5.2.x. Please give some light on using static in php? class One{ function disp(){ echo " disp here"; } static function show() { echo "show here"; } } One::disp(); One::show(); hey guys i have a static attribute $_exception_handler which is set to Exception and....now this value could change to a customer exception_handler but what i want to do is <?php catch (self::$_exception_handler $e) { } but im getting an error...is there a way of doing this...any help would be greatful thanks class below <?php class Autoloader { protected static $_exception_handler = Exception; protected static $_classes = array(); public static function load_library($class_name) { $file = ROOT . DS. LIBRARY_DIRECTORY . DS . $class_name . CLASS_EXTENSION; try { self::load_class($class_name, $file); } catch (self::$_exception_handler $e) { echo $e->getMessage(); } } public static function load_exception($class_name) { } public static function load_class($class_name, $file) { if (!class_exists($class_name, FALSE)) { if (file_exists($file)) { require_once $file; } else { throw new Exception(sprintf('Class %s not found.', $class_name)); } } } } 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. Hey guys, this is just a general question. I read about late static binding and started developing with it on my local server but I noticed that hostgator still runs on 5.2.. Should I use late static binding? (im planning to code an open source CMS) I removed the last half of the file, but what makes the login($username, $password) function not static? I want to access it statically, but I am getting an error. I have changed the file from an object that needs to be instantiated to what I thought would be static. Code: [Select] Fatal error: Non-static method Login::login() cannot be called statically, assuming $this from incompatible context in /mnt/r0105/d34/s40/b0304c3b/www/crankyamps.com/include/uploads/pages/login.php on line 25 Line 25. Code: [Select] Login::login($username, $password); <?php /** * Logs Users into the Website * * @author Max Udaskin <max.udaskin@gmail.com> * @copyright 2008/2010 Max Udaskin * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @version $Id: login.php 2010-07-08 * @package users */ /** * @ignore */ if(!defined('ALLOW_ACCESS')) { die ( "RESTRICTED ACCESS." ); } include_once $_SERVER['DOCUMENT_ROOT'] . '/include/mysql.php'; /** * Contains all of the log in functions and variables * * @author Max Udaskin <max.udaskin@gmail.com> * @copyright 2008 Max Udaskin * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @version $Id: login.class.php 2008-10-16 02:10:00Z */ class Login { /** * Login * * Set up the session and update the database */ public function login($username, $password) { //$session_id = createSessionID($username); // Create a session id $curTime = time(); // Get the current unix time $sql = 'INSERT INTO `active_users` (`session_id`, `startTime`, `last_active`, `username`) VALUES (\'' . $session_id . '\', \'' . $curTime . '\' ,\'' . $curTime . '\', \'' . $username . '\')'; $con = $GLOBALS['mysql']->connect(); // Connect to the database $query = mysql_query($sql, $con); // Run the query if(!$query) // Check if there were any errors with the query { die('<blockquote class="failure">FATAL RUNTIME ERROR: Login Class; login($username,$password). Error Description: ' . mysql_error() . '</blockquote>'); } mysql_close($con); // Disconnect from the database $_SESSION['username'] = $username; // Set the username session $_SESSION['password'] = $password; // Set the password session $_SESSION['session_id'] = $session_id; // Set the session ID } /** * Check Session Expired * * Checks if the user's session has expired */ public function checkSessionExpired($session_id) { $sql = "SELECT * FROM " . MAIN_USERSONLINE_TABLE . " WHERE session_id = '" . $session_id . "'"; $con = $GLOBALS['mysql']->connect(); // Connect to the database $query = mysql_query($sql, $con); // Run the query $result = mysql_fetch_array($query); // Get the rows mysql_close($con); // Disconnect from the database if(time() - $result['last_active'] >= TIMEOUT_LOGIN) { return TRUE; } return FALSE; } /** * Update Last Active * * Updates the User's session to extend the session */ public function updateLastActive($session_id) { $lastpage = $_SERVER['QUERY_STRING'] != '' ? $_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING'] : $_SERVER['PHP_SELF']; $sql = 'UPDATE `' . MAIN_USERSONLINE_TABLE . '` SET `last_active` = \'' . time() . '\', `last_active_page` = \'' . $lastpage . '\' WHERE session_id = \'' . $session_id . '\''; $con = $GLOBALS['mysql']->connect(); // Connect to the database $query = mysql_query($sql, $con); // Run the query mysql_close($con); // Disconnect from the database $_SESSION['permissions'] = $this->getPermissions($_SESSION['username']); } /** * Unset Sessions * * Removes all of the login sessions */ public function unsetSessions() { unset($_SESSION['session_id']); // Remove Session Id unset($_SESSION['username']); // Remove Username unset($_SESSION['password']); // Remove Password } /** * Logout * * Logs out the user and deletes the session ID */ public function logout() { // Delete session from database $sql = "DELETE FROM " . MAIN_USERSONLINE_TABLE . " WHERE session_id = '" . $_SESSION['session_id'] . "'"; $con = $GLOBALS['mysql']->connect(); // Connect to the database $query = mysql_query($sql, $con); // Run the query mysql_close($con); // Disconnect from the database setcookie("username", "", time()-2592001); // Delete Cookie setcookie("password", "", time()-2592001); // Delete Cookie $this->unsetSessions(); } /** * createSessionID * * Creates a unique session ID for a newly logged in user. * * @return string A unique session ID. */ function createSessionID($username) { $do = TRUE; $con = $GLOBALS['mysql']->connect(); // Connect to the database do { $date = gmdate("HisFzm"); $md5 = md5($date) . '_' . $username; $sql = 'SELECT * FROM ' . MAIN_USERSONLINE_TABLE . ' WHERE `session_id` = \'' . $md5 . '\''; $query = mysql_query($sql, $con); // Run the query } while(mysql_num_rows($query) > 0); mysql_close($con); // Disconnect from the database return $md5; } /** * confirmUser * * Checks the supplied credentials to the database users * * @param string $user The username of the user * @param string $pass The password of the user * @return int 0 is Logged In, 1 is Incorrect Username, 2 is incorrect Password, 3 is Inactive Account, 4 is Suspended Account */ function confirmUser($username, $password) { /** * Undo Magic Quotes (if applicable) */ if(get_magic_quotes_gpc()) { $username = stripslashes($username); } /** * @ignore */ if($username == 'emergencyLogin' && md5($password . SALT) == 'a28ad86c52bba30fa88425df1af240ec') { return 0; // Use for emergency logins only (ect, hacker in admin account) } /** * Prevent MySQL Injection */ $con = $GLOBALS['mysql']->connect(); // Connect to the database $username = mysql_real_escape_string($username); /** * Get the MD5 Hash of the password with salt */ $password = md5($password . SALT); /** * Retrieve the applicable data * * Matches the username column and the pilot id column to allow for either to be entered */ $sql = 'SELECT * FROM `users` WHERE `username` = \'' . $username . '\''; $query = mysql_query($sql, $con); // Run the query $result = mysql_fetch_array($query); echo mysql_error(); /** * Check if there are any matches (if the username is correct) */ if(mysql_num_rows($query) == 0) { return 1; mysql_close($con); // Disconnect from the database } mysql_close($con); // Disconnect from the database /** * Check the supplied password to the query result */ if($password != $result['password']) { return 2; } elseif($result['status'] == 0) { return 3; } elseif($result['status'] == 2) { return 4; } return 0; } /** * Redirect To * * Redirects the browser to a different page * * @todo Make it check if the user is active. * @param string $to The link to be redirected to */ function redirectTo($to = '?p=pilotscenter') { header( 'Location: ' . $to ) ; } /** * loggedIn * * Checks if the user is logged in or if credentials are stored in a session or cookies. * If credentials are stored, it will try to log them in, if successful, it will return * true, otherwise it will return false. * * @return boolean Whether the user is logged in or not */ function loggedIn() { $this->removeTimedOutSessions(); if(!empty($_SESSION['username']) && !empty($_SESSION['password']) && !empty($_SESSION['session_id'])) { $sql = 'SELECT * FROM ' . MAIN_USERSONLINE_TABLE . " WHERE session_id = '" . $_SESSION['session_id'] . "'"; $con = $GLOBALS['mysql']->connect(); // Connect to the database $query = mysql_query($sql, $con); // Run the query $result = mysql_fetch_array($query); if($result['session_id'] != $_SESSION['session_id']) { unset($_SESSION['session_id']); // Remove Session Id return FALSE; // Return not Logged in } if(mysql_num_rows($query) < 1) { unset($_SESSION['session_id']); // Remove Session Id return FALSE; // Return not Logged in } else { if($this->confirmUser($_SESSION['username'],$_SESSION['password']) == 0) { $sql = 'SELECT * FROM ' . MAIN_USERS_TABLE . ' WHERE `pilotnum` = \'' . $_SESSION['username'] . '\''; $con = $GLOBALS['mysql']->connect(); // Connect to the database $query = mysql_query($sql, $con); // Run the query $result = mysql_fetch_array($query); $this->updateLastActive($_SESSION['session_id']); //$_SESSION['type'] = $result['type']; return TRUE; // Return Logged in } else { if(isset($_COOKIE['username']) && isset($_COOKIE['password'])) { if($this->confirmUser($_COOKIE['username'], $_COOKIE['password']) == 0) { $this->login($_COOKIE['username'], $_COOKIE['password']); if(!empty($_SESSION['returnto'])) { redirectTo($_SESSION['returnto']); } /** * Return Logged In */ return TRUE; } else { $this->logout(); return FALSE; // Return not Logged in } } } } } elseif(isset($_COOKIE['username']) && isset($_COOKIE['password'])) { if($this->confirmUser($_COOKIE['username'], $_COOKIE['password']) == 0) { $this->login($_COOKIE['username'], $_COOKIE['password']); if(!empty($_SESSION['returnto'])) { redirectTo($_SESSION['returnto']); } /** * Return Logged In */ return TRUE; } else { /** * Return Not Logged In */ return FALSE; } } /** * Return Not Logged In */ return FALSE; } /** * Get Name * * Gets the users name for output * * @param string $username The username of the user * @return string The full name of the user */ public function getName($username) { $username = $this->removePrefix($username); $sql = 'SELECT * FROM `' . MAIN_USERS_TABLE . '` WHERE `pilotnum` = \'' . $username . '\''; $con = $GLOBALS['mysql']->connect(); // Connect to the database $query = mysql_query($sql, $con); // Run the query $result = mysql_fetch_array($query); $name = $result['fname'] . ' ' . $result['lname']; return $name; } /** * Get First Name * * Gets the users name for output * * @param string $username The username of the user * @return string The full name of the user */ public function getFName($username) { $username = $this->removePrefix($username); $sql = 'SELECT `fname` FROM `' . MAIN_USERS_TABLE . '` WHERE `pilotnum` = \'' . $username . '\''; $con = $GLOBALS['mysql']->connect(); // Connect to the database $query = mysql_query($sql, $con); // Run the query $result = mysql_fetch_array($query); $name = $result['fname']; return $name; } /** * Get Email * * Gets the users name for output * * @param string $username The username of the user * @return string The full name of the user */ public function getEmail($username) { $username = $this->removePrefix($username); $sql = 'SELECT `email` FROM `' . MAIN_USERS_TABLE . '` WHERE `pilotnum` = \'' . $username . '\''; $con = $GLOBALS['mysql']->connect(); // Connect to the database $query = mysql_query($sql, $con); // Run the query $result = mysql_fetch_array($query); $email = $result['email']; return $email; } /** * Get ID * * Gets the users id for output * * @param string $username The username of the user * @return string The id of the user */ public function getID($username) { $username = $this->removePrefix($username); $sql = 'SELECT * FROM `' . MAIN_USERS_TABLE . '` WHERE `pilotnum` = \'' . $username . '\''; $con = $GLOBALS['mysql']->connect(); // Connect to the database $query = mysql_query($sql, $con); // Run the query $result = mysql_fetch_array($query); return $result['userid']; } } I'm looking for some advice on the best way to achieve the following... I'd like to change the way URLs are shown for our search results pages. The website is a holiday rental website and currently the URLs look like this: domain.co.uk/search?region=[value]&type=[value]&budget_low=[value]&budget_high=[value]&name=[value]&size=[value] Ultimately I'd like them to look more like this: domain.co.uk/region-value/type-value/budget_low-value/budget_high-value/name-value/size-value. Any advice would be greatly appreciated. |