PHP - Simple Oop Question: Best Practice For Site-wide Constants
What is the best practice for using site-wide constants in a class?
E.g. COMPANY_NAME is set in a config file and used on many pages. How would it be best to use this in a class. I'm guessing just calling COMPANY_NAME anywhere in the class would not be considered best practice. Thanks. Similar TutorialsHey guys, Why exactly do people use multiplication when calculating time? Like when setting cookies, timeouts or something that requires second-based definitions. For example, some do: Code: [Select] $thirty_days = time()+60*60*24*30; As opposed to what I do: Code: [Select] $thirty_days = time()+2592000; Why do they do that? Does it help them calculate it without a calculator? Make it easier to manage/adjust in the future? Personal preference? These are the only possible explanations I can think of. This has been bugging me for a while...am I doing something wrong? Greetings all, I like to make a config.php file and place it outside my document root for security. I do this all the time. Then just inlcude the config in any file that I need information for. include('../includes/config.php'); This works most of the time for any DB connection information a piece of code might need. However, sometimes I like to place all my functions in a file called functions.php to keep them separate and have a single place to work with them. I have not done any coding in about two years and just started back and for the life of me I can't get any connection attempt inside any of my functions to use the DB connection info from the config.php even if I include the file right inside the functions.php at the top. Even when I put all my functions inside the config file itself they still have no access to the connection vars. I remember that I used to be able to use a global so some type to do this. The important part is getting DB connection access to any functions that I write. Here is an example of a plain config that I might start with; //* Database connection information.. *// $DBHost="localhost"; //* Database Hostname $DBName="some_db"; //* Database Name $DBUser="some_user"; //* Database Username $DBPass="some_pass"; //* Database Password $db = mysql_connect($DBHost, $DBUser, $DBPass); mysql_select_db($DBName); Can someone show me where I'm going wrong and the modern excepted method of doing this? I would greatly appreciated it!! Thank you. I don't really have an issue with my script... I simply want to know if it is a bad practice to create a script that recurses through your root directory and zips up everything into one large zip file... I am creating a backup deal for my site and my site is rather large... Is this considered bad practice? Hi, I would like to build a website that has similar functions to www.thetextpage.com Mainly i want to know how i could link a field that houses a price, to paypal and once payment has been confirmed, some text is update to a website. in real time. please reply if you don't understand and i can go further into the idea. regards Hey all, Another OOP question from me Is using constants in a class a bad idea? For example I have a config file and have this in a class: header("Location: ".LOGIN_LOCATION); Also is it OK to define $_SERVER variables in a construct? For example I have: class whatever { private $_remote_addr; private $_user_agent; function __construct() { $this->_remote_addr = $_SERVER['REMOTE_ADDR']; $this->_user_agent = $_SERVER['HTTP_USER_AGENT']; } .. or is it OK just to use $_SERVER for example in a mysql query? Thanks for all the help so far. Getting there! I would like to define two constants to switch where my "Web Root" is located so I can go between my laptop and web host. I created a "config.inc.php" Code: [Select] <?php // Constants for Web Roots. define('DEV_ROOT', '/00_MyWebsite/'); define('PROD_ROOT', 'w w w.MyWebsite.com/'); ?> and then in my "checkout.php" page I have... Code: [Select] <body> <!-- Access Web Root Constants --> <?php require_once "../config.inc.php"; echo 'DEV _ROOT = ' . DEV_ROOT; echo 'PROD _ROOT = ' . PROD_ROOT; ?> But that doesn't seem to work so far. I know what I'm trying to do, but am getting stuck on how to do it?! Can someone help straighten me out?? Thanks, Debbie Hello all, I was just reading the PHP manual and came across this example that doesn't work right for me. Anyone know why this is so? Tried looking through the manual for this but found nothing about it.. $s = 'monkey'; $t = 'many monkeys'; printf("[%s]\n", $s); // standard string output printf("[%10s]\n", $s); // right-justification with spaces printf("[%-10s]\n", $s); // left-justification with spaces printf("[%010s]\n", $s); // zero-padding works on strings too printf("[%'#10s]\n", $s); // use the custom padding character '#' printf("[%10.10s]\n", $t); // left-justification but with a cutoff of 10 characters The above example will output: [monkey] [ monkey] [monkey ] [0000monkey] [####monkey] [many monke] But when i tried this for myself, printf("[%10s]\n", $s);does not left pad the output as so : [ monkey].Instead it outputs [ monkey]. But adding a 0 as so : printf("[%010s]\n", $s);, pads it with 4 0's, outputting : [0000monkey] . Is there some other way to make it pad spaces that i'm missing? Running PHP 5.3.2 This might be a very easy problem to solve. I am literally brand new to php. I am trying to create a simple site that will load content depending on what page 'id' is in the URL and if it doesn't exist to show a page for that scenario. eg index.php?id=1 will show the page 1.php It works fine apart from showing an error when there is no id at all, eg www.website.com will show an error but www.website.com/index.php?id=1 will show a page I want to be able to show the homepage if there is no 'id' at all. Code: [Select] <?php $id = $_GET['id']; if(file_exists("./".$id.".php")) { include ("./".$id.".php"); } else { include ("404.php"); } ?> Any help is appreciated Thanks Hi, I have a small CMS I coded and developped on my local WAMP server and everything worked fine but when I decided to export everything to my hostgator server I realized that the constants I define in some of my includes are not being defined.. Here is one of the errors I get : Code: [Select] Fatal error: require_once() [function.require]: Failed opening required 'LIB_PATHDSdatabase.php' (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/nethox/public_html/photo_gallery/includes/photograph.php on line 2 You can see that LIB_PATH is not defined and even the .DS. is not working.. Here is a sample of the code I made : Code: [Select] <?php // Defining core paths // Defining them as absolute paths to make sure that require_once works as expected // DIRECTORY_SEPARATOR is a PHP pre-defined constant // (will do \ for Windows, / for Unix) defined('DS') ? null : define('DS', '/'); defined('SITE_ROOT') ? null : define('SITE_ROOT', 'http://www.lemontree-designs.com'.DS.'photo_gallery'); defined('LIB_PATH') ? null : define('LIB_PATH', SITE_ROOT.'/includes'); defined('LOG_PATH') ? null : define('LOG_PATH', SITE_ROOT.DS.'logs'); defined('PUBLIC_AREA') ? null : define('PUBLIC_AREA', 'http://www.lemontree-designs.com'.DS.'photo_gallery'.DS.'public'); // Load config file first require_once(LIB_PATH."/config.php"); // Load basic functions next so that everything after can use them require_once(LIB_PATH.DS."functions.php"); // Load core objects require_once(LIB_PATH.DS."session.php"); require_once(LIB_PATH.DS."database.php"); require_once(LIB_PATH.DS."pagination.php"); // Load database-related classes require_once(LIB_PATH.DS."user.php"); require_once(LIB_PATH.DS."photograph.php"); require_once(LIB_PATH.DS."comment.php"); ?> Any help is appreciated! EDIT : For the sake of debugging, I've changed the defined value of DS to '/' instead of DIRECTORY_SEPARATOR to see if it's what caused an issue.. Does anyone know how to echo a defined constant without using concatenation? something like Code: (php) [Select] <?php define("CONST", "VALUE"); echo <<<END Some html and my Const = CONST END; ?> This works but I want the var to be const Code: (php) [Select] <?php $CONST = "VALUE"; echo <<<END Some html and my Const = $CONST END; ?> Thanks for your replies This is probs. an easy one but I have in my database some values, these values are defined constants in my php code. How do I display the value of the constant not the text (constant name)? Often in the very beginning of index.php, I will define a bunch of constants. To make sure I can quickly identify them as being one of my defined constants, I will often include some sort of prefix.
define ('xzy_somecontant',123); define ('xzy_anothercontant',321);Sometimes I have a bunch of constants that are related; define ('xzy_id_for_page1',123); define ('xzy_id_for_page2',231); define ('xzy_id_for_page3',312);It would be nice to somehow group them into say "xzy_page_ids", and then access them by some index such as "page1" or "1" (or whatever makes sense for the given naming structure). Is this possible? Is there another defacto way of doing so such as a static class or something? Thanks Some questions about PHP Constants... 1.) What make a Constant "come to life"? 2.) What is the life of a Constant? 3.) Can you define a Constant in "file_1.php" and use the Constant in "file_2.php" and "file_3.php"?? Debbie I've been working on a registration form and it seems like the better I get at solving more complex issues the smaller issues plague me the most. I've got the following function: //process database actions function process_database($post) { global $table; //connect to database $connect_db = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME); //check database connection if ($connect_db->connect_error) { return false; } else { if ($stmt = $connect_db->prepare( "INSERT INTO $table (firstname, lastname, username, email, password) VALUES ( ?, ?, ?, ?, ? )" ) ) { $stmt->bind_param(NULL, $firstname, $lastname, $username, $email, $password); $firstname = $post['firstname']; $lastname = $post['lastname']; $username = $post['username']; $email = $post['email']; $password = $post['password']; if (!$stmt->execute()) { return false; } } } return true; } This is in a functions.php file. The issue is in the $connect_db assignment that has the constants from the config.php file in it. That file looks like this: <?php ob_start(); session_start(); $timezone = date_default_timezone_set("America/xxxxxxx"); $whitelist = array('username', 'email', 'email2', 'password', 'password2'); //TODO here I've removed firstname and lastname from the whitelist as they're optional //may add them back and try to iterate around them in the future $table = 'users'; define('DB_HOST', 'localhost'); define('DB_USERNAME', 'root'); define('DB_PASSWORD', ''); define('DB_NAME', 'means'); $conn = mysqli_connect(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME); if($conn->connect_errno) { printf("Connect Failed: %s\n", $conn->connect_error); exit(); } ob_end_flush(); ?> The constants defined in config.php are not being recognized in functions.php. I understand that constants are global and available throughout a script. I've connected to two files with the following line: //require config file require_once($_SERVER['DOCUMENT_ROOT'] . '/../config/config.php'); as I have the config/config.php outside htdocs. I know this works because of a db query to check uniqueness of username that works properly. Why are these constants coming back as undefined in the process_database().function.php? Nothing I've tried works and I've run out of ideas. TIA Code: [Select] <?php class constantTest { const HELLOWORLD = 'maybe not'; function __construct() { echo HELLOWORLD; // Output: HELLOWORLD echo constant('HELLOWORLD'); // Output: Warning: constant() [function.constant]: Couldn't find constant HELLOWORLD echo self::HELLOWORLD . "\n"; // Output: maybe not } } $bob = new constantTest(); I have read through the manual but as far as I can see all three methods should output the constant rather than just the last one. Question: Why? I am following a book and need help setting up Path Constants. Here is the script I need to adjust... // Constants define('BASE_URI', '/path/to/Web/parent/folder/'); define('BASE_URL', 'www.example.com'); define('MYSQL', '/path/to/mysql.inc.php'); Since I am working in NetBeans, I do not have access above my Project Folder which serves as my "Web Root". So if my Project Folder is called "MyProjectFolder", and I want both BASE_URI and BASE_URL to point to that directory on my laptop, what should I put? I'm thinking something like this... // Constants define('BASE_URI', '/'); define('BASE_URL', '/'); define('MYSQL', '/includes/mysql.inc.php'); TomTees Hey guys Anyone know the correct syntax to put a constant inside a header? this is driving me crazy with RPATH being my constant header("Location: ".RPATH."admin/monitor.php"); Can you echo class constants? This does not work for me. echo “here is a class constant: self::CLASS_CONSTANT”; // using double quotesInstead I *must* concatenate it: echo ‘here is a class constant: ‘ . self::CLASS_CONSTANT;But of course I do not have to do this with a normal variable, which will echo a variable fine: echo “my name is $name_variable”;Am I doing something wrong or is this normal behavior? Edited by E_Leeder, 30 October 2014 - 11:04 AM. I sometime pass configuration settings as an associate array... public function __construct(JsonValidatorMethods $methods, array $options) { foreach($options as $option) { //validate whether valid and if so set $this->$option. Options not provided will default to their private $strictMode=true value } } $validator=new JsonValidator($methods, ['sanitize'=>true, 'strictMode'=>true, 'setDefault'=>false]); And other times pass them as individual arguments... public function __construct(JsonValidatorMethods $methods, bool $sanitize=false, bool $strictMode=false, bool $setDefault=true) {} $validator=new JsonValidator($methods, true, true, false); I have a class which I was doing the later and also which I wish to allow them to be first set in the constructor but also specified when calling some of the public methods. It became a pain to pass all the individual flags to each private method, so I thought I would give bitmask constants a try as shown below. I recognize that this approach only allows booleans to be passed, but I am okay with this. The part I am not sure about is how best have default values. For instance, maybe the default is $this->options=0b0110, 0b1100 is passed to the constructor, and 0b1 (aka 0b0001) is passed is passed to the public method. The high three bits in 0b0001 just are not provided, but how can I not interpret them as explicitly false? Also, a little off topic, but am I implementing this bitmask approach correctly, and any strong options whether one of these three approaches or some totally other approach is best? Thanks class JsonValidator { //Use provided options const SANITIZE = 0b0001; //Whether to sanitize (i.e. 'false' is changed to false) const STRICTMODE = 0b0010; //Currently only enfources that boolean is true/false (instead of 1/0 or "true"/"false") const SETDEFAULT = 0b0100; //If true, type double and value "nan" will be converted to 0, etc. private $methods, $options; static public function create(int $options=0):self { return new self(new JsonValidatorMethods, $options); } static public function getOption(array $options):int { $o=0; foreach($options as $option) { if(!defined("self::$option")){ throw new JsonValidatorErrorException((is_string($option)?$option:'given constant').' is not valid'); } $o=$o|constant("self::$option"); } return $o; } public function __construct(JsonValidatorMethods $methods, int $options=0) { $this->methods=$methods; $this->options=$options; } public function validate(array $input, array $rules, int $options=0){ $options=$options|$this->options; if($options & self::SANITIZE) { $value=$this->sanitize($input, $rules, $options); } } private function sanitize(array $input, array $rules, int $options=0){} } $validator=new JsonValidator($methods, JsonValidator::SANITIZE|JsonValidator::SETDEFAULT); Edited June 27, 2019 by NotionCommotion Nevermind => Maybe I should start my constants with high bit set such as const SANITIZE = 0b1000; I have defined my database connection data as constants in a separate file for security reasons. How can I simply access the data stored in those constants. I have to call the file to get the value of the constants. If I inadvertently call the file twice in a script using an include or require statement, I get an error that I am trying to define the constants again. Can I somehow just call the constants without including the file where they are defined? --Kenoli |