REMEMBER PHP

MINTE9
2REMEMBER




Last update:   23-07-2021

Constants

A constant can't be changed once set. A constant can be accessed for any scope within a script. A constant can contain ony scalar values.
 
error_reporting(E_ALL);

define('CCC', '1');
define('CCC', '2'); // Notice: Constant CCC already defined 
... 3 lines
˄˄˄
 
define('CCC', 1);

function foo() { 
    echo CCC; 
}

foo(); // 1  
... 5 lines
˄˄˄
 
define('CCC', array(1)); // Wrong parameter count for define() 
... 1 lines
˄˄˄
! If you want to see if a constants exists, use defined(), isset() only applies to variables. Note the use of quotes, this is important.
 
echo defined('AAA') ? 1 : 0; // output 0
... 1 lines
˄˄˄
Class Constant    (2/4)

Class constant

For class constant use const.
 RunCode
class myClass {

   const CCC = 1;

   public function  __construct() {

       echo defined('self::CCC') ? 1 : 0; // 1
    }
}

new myClass();
... 7 lines
˄˄˄
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    
... 4 lines
˄˄˄
Magic Constants    (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)
... 7 lines
˄˄˄
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
... 6 lines
˄˄˄
Task

 CompleteTask
/**
 * Define getMaxValue() method
 * Be aware of the static method call
 */
class MyClas {

    const MAX_VALUE = 100;

    // ...
}

echo MyClass::getMaxValue(); // 100
solution code
Questions    
No. 3   Control structures
CARD
02

        A B C D E F
🔔
1/4