Memory App
Programming
 




Define

A constant can't be changed once set.

error_reporting(E_ALL);

define('CCC', '1');

define('CCC', '2'); // Notice: Constant CCC already defined
Can be accessed for any scope within a script.

define('CCC', 1);

function foo() { echo CCC; }

foo(); // output 1
Can contain ony scalar values.

define('CCC', array(1)); // Wrong parameter count for define()
They follow the same naming requirements as variables:

define('1CCC', 1); // Invalid name
(1/4)

Defined

If you want to see if a constants exists, use defined() as isset() only applies to variables:

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 (2/4)

Class constant


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():

error_reporting(E_ALL);

define('CCC', '1');

defined('CCC') || define('CCC', '2'); // avoid getting Notice

echo CCC; // output 1    
(3/4)

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

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


Questions



Top Reference > Programming
0/0 (80)  
Not Logged