ExpertRefresh

Basics / Constants definition  

Related Pages

Basic syntax
Numeric type
String type
Boolean type
Constants definition
Control structures
Reference


0.0% 100%
 
 
0 pages 298 questions
1) What constant definition is correct?






2) What is the output for the following script? <?php error_reporting(E_ALL & ~E_NOTICE); define('CCC', '1'); define('CCC', '2'); echo CCC;





3) What is the output for the following script? <?php error_reporting(E_ALL); define('CCC', '1'); defined('CCC') || define('CCC', '2'); echo CCC;








Can not be changed once set: <?php error_reporting(E_ALL); define('CCC', '1'); define('CCC', '2'); // Notice: Constant CCC already defined Can be accessed for any scope within a script: <?php define('CCC', 1); function foo() { echo CCC; } foo(); // output 1 Can only contain scalar values: <?php define('CCC', array(1)); // Wrong parameter count for define() They follow the same naming requirements as variables: <?php define('1CCC', 1); // Invalid name If you want to see if a constants exists, use defined() as isset() only applies to variables: <?php echo defined('AAA') ? 1 : 0; // output 0 // Note the use of quotes, this is important. This example is checking // if the string 'AAA' is the name of a constant named AAA For class constant is defined use self:: <?php class myClass { const CCC = 1; public function __construct() { echo defined('self::CCC') ? 1 : 0; } } new myClass(); To avoid getting Notice check if constant exists use defined(): <?php error_reporting(E_ALL); define('CCC', '1'); defined('CCC') || define('CCC', '2'); // avoid getting Notice echo CCC; // output 1

Magic constants

There are changing, depending on where they are used. __LINE__ (curent line number of file) __FILE__ (fullPath/filename) __DIR__ (directory of a file; dirname(__FILE__) equivalent) __FUNCTION__ (function name) __CLASS__ (class name) __METHOD__ (the class method name) __NAMESPACE__ (current namespace)

Errors

Several configuration directives in the php.ini file allow you to finetune how and which errors are reported. <?php ini_set('display_errors', '0'); // errors are not outputted to the script's output; default is 1 error_reporting(E_ALL & ~E_NOTICE); // reporting of all errors, except notices ini_set('log_errors', '1'); // error messages will be logged to server; default is 0


References