note 129225 added to function.define

From: Date: Wed, 07 Feb 2024 21:36:59 +0000
Subject: note 129225 added to function.define
Groups: php.notes 
Request: Send a blank email to php-notes+get-221179@lists.php.net to get a copy of this message
As user defined constants are available throughout an app and configuration for a an app would benefit from being available nearly everywhere also why not combine the use-case and create a global user defined constant SETTINGS with <?php if(!defined('ROOT')) { define('ROOT', $_SERVER['DOCUMENT_ROOT'] . '/'); } if( !defined( 'SETTINGS_FILE' ) ) { define( 'SETTINGS_FILE', ROOT. 'settings.ini' ); } if( !defined( 'SETTINGS' ) ) { define( 'SETTINGS', parse_ini_file( SETTINGS_FILE, true ) ); } ?> In here ROOT will have the path to the root of the application SETTINGS_FILE a default name of a settings file and parse_ini_file is used to populate the constant. Note: This will work only with PHP 7 and higher. Use the SETTINGS constant for instance to connect a database: <?php $dsn = 'mysql:host=' . SETTINGS['db']['hostname'] . ';dbname=' . SETTINGS['db']['database']; $db= new \PDO( SETTINGS['db']['username'], SETTINGS['db']['password'], [ \PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8", \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION ] ); ?> with a settings.ini file containing [db] hostname=hostname database=database username=username password=password ---- Server IP: 45.112.84.4 Probable Submitter: 80.90.13.131 (proxied: 217.23.3.171) ---- Manual Page -- https://php.net/manual/en/function.define.php Edit -- https://main.php.net/note/edit/129225 Del: integrated -- https://main.php.net/note/delete/129225/integrated Del: useless -- https://main.php.net/note/delete/129225/useless Del: bad code -- https://main.php.net/note/delete/129225/bad+code Del: spam -- https://main.php.net/note/delete/129225/spam Del: non-english -- https://main.php.net/note/delete/129225/non-english Del: in docs -- https://main.php.net/note/delete/129225/in+docs Del: other reasons-- https://main.php.net/note/delete/129225 Reject -- https://main.php.net/note/reject/129225 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#221179) next »