PHP - Isn't Accessing A Static Variable From A Non-static Function Bad?
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? Similar TutorialsHi 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! 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.
I have the following static method: public static function query($query){ self::$num_queries++; return mysql_query($query)or die(mysql_error()); } I then call it like this: $oql = Mysql::query("SELECT first FROM members WHERE member_id = '{$this->owner}'"); $rql = mysql_fetch_assoc($oql); I then get the following error: Quote Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /incl/php/classes/Photo.php on line 13 Why am I getting this error? so my situation is something like this , i'm trying to fetch user details based on `id` that isset is getting, but some how the `variable that contains the $_GET value doesn't work` in query but when i put an static value to pdo query then it works and show the result. i have checked by doing `var_dump` of variable `$user` before query and it shows the correct value but not working in query. Below is the code i'm working with: 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? Question 1) Is the only and proper way to call a parent function "parent::function()"? Are there other/better ways from within a child function? Question 2) What are the deciding factors for when to make a function or attribute static? How do you make that decision? Assuming 5.3... Thanks. 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 Hi, I have been trying to improve my PHP programming skills by following the Lynda.com Beyond the basics tutorial and they came to a section where they were building common database methods inside a database class. Since they did not have PHP 5.3 (Where late static bindings is introduced) they had to place code referring to self:: inside of each class that needs this functionality. It seems that not having late static binding was binding self to the database class and not to other classes that call it statically. I will insert some code to explain this better. Long story short, I was really interesting in getting an attributes function working and as I do not have late static bindg either, I cannot figure out how to call it from inside a class to make it function correctly. Here is some code. Below is the attribute class they wrote. Each class declared an array of attributes for each of the classes that want to call this method like protected static $db_fields = array('id', 'email', 'password', 'etc'); Code: [Select] protected function attributes() { // return an array of attribute names and their values $attributes = array(); foreach(self::$db_fields as $field) { if(property_exists($this, $field)) { $attributes[$field] = $this->$field; } } return $attributes; } They planned on moving this code to a DatabaseObject class after they get LSB but until then, have to include it in every class that wants use this. Is there any way to write this as a function, include it in a class, and call the method without late static binding.. or even place this inside a database class and call it from another class without LSB? Forgive me if I am not explaining this correctly, again, I am still learning. My version of PHP is 5.2.6. I am trying to write a more elegant solution to be able to check an object, find only the properties in an object that have values, and update those values in a database with a matching ID. I am extending a class from a generic user class here is an example of my code Code: [Select] <?php require_once('User.php'); require_once('Database.php'); class Vendor extends User { protected static $vendor_attributes = array('id', 'nothing' , 'tagline' , 'bio'); protected static $table_name = "user_vendors"; public $tagline; }//close class ?> Hello all, I have some piece of code that is nested like this $variable = 'This is a global argument'; function parentFunction($variable) { function childFunction() { echo 'Argument of the parent function is '.$GLOBALS['variable']; } childFunction(); } parentFunction(5); What I want to know is - Is there a way to access a variable from the parent function without passing arguments to the child function? (Something like how classes have parent::?). I don't want to use $GLOBALS because it might cause some variable collision, and I didn't want to pass arguments because incase I decide to change the arguments in the parent function I'd have to do it in the child function aswell. From my searching around in the Internet it seems like this is not possible, but if theres a slight chance that there might be something out there, i'm willing to give it a shot . Thanks in advance 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 } 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)); } } } } 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(); 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. 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']; } } 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 have a bunch of quasi-static values that must be available to the application. Most of them are set based on settings in a configuration file. Others are based on GET, COOKIE, or SESSION values, and utilize the database to get the actual values. The values will never be written to or modified by the application, only read.
It seems to me that I could create some sort of superclass which includes static methods and properties, and I could access any value by something like superclass::get('some.value'); I could design the class so that the values are queried from the DB or obtained from a parsed file only the first time they are requested, and for future requests, retrieved from a static property.
That being said, I have been told from more than one person that I am just doing it "wrong".
Please let me know what is wrong about it.
Thank you
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. 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]); } } I finally got my kml to display through the static maps api thinking I could then display my map on the pdf I'm generating using mpdf. But, it is not displaying the image in the pdf. It works fine on a blank test page.
$kmlMap = "<img src=\"http://maps.googleapis.com/maps/api/staticmap?zoom=15&size=500x300&maptype=hybrid&path=color:0xff0000ff|weight:3|$correctedCoords \" /><br />";Any ideas on how I could make this work with mpdf? |