PHP - Class Constants
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? Similar TutorialsCan 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. 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 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.. 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 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)? 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 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 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"); 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 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 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; Well hello there, I want to create a script that writes a few PHP constants to a file called config.php. It does not work however, with the way I wrote it as below: Code: [Select] $configdata = "<?php //Configuration File \define("DBHOST", $dbhost); //DB Hostname \define("DBUSER", $dbuser); //DB Username \define("DBPASS", $dbpass); //DB Password \define("DBNAME", $dbname); //Your database name \define("DOMAIN", $domain); //Your domain name (No http, www or . ) \define("SCRIPTPATH", $scriptpath); //The folder you installed this script in \define("PREFIX", $prefix); ?>"; $file = fopen('../inc/config.php', 'w'); fwrite($file, $configdata); fclose($file); I am getting this error 'syntax error, unexpected T_STRING in ...', and I have no idea how to fix it. Strangely the below codes using PHP variables work flawlessly: Code: [Select] $configdata = "<?php //Configuration File \$dbhost = '{$dbhost}'; //DB Hostname \$dbuser = '{$dbuser}'; //DB User \$dbpass = '{$dbpass}'; //DB Password \$dbname = '{$dbname}'; //Your database name \$domain = '{$domain}'; //Your domain name (No http, www or . ) \$scriptpath = '{$scriptpath}'; //The folder you installed this script in \$prefix = '{$prefix}'; ?>"; //Write the config.php file... $file = fopen('../inc/config.php', 'w'); fwrite($file, $configdata); fclose($file); This confuses me, all I did was to change the string to output from a list of variables to a list of constants, and it gives weird errors that I have absolutely no idea how to fix. Can anyone please lemme know what I did wrong? Thanks. 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. 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 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 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? 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 |