minte9
LearnRemember / PHP



Constants

A constant can't be changed once set.
 
/**
 * Constants can be defined using the const keyword ...
 * or by using the define()
 * 
 * Can't be changed once set.
 * Can be accessed for any scope within a script.
 */

error_reporting(E_ALL);

define('A', '1');

// const A = 1; // Warning: Constant A already defined 
const B = 2;
const C = array(3);

{ 
    echo A;     # 1
    echo B;     # 2
    echo C[0];  # 3
}

Class

The default visibility of class constants is public.
 
/**
 * Class constants are allocated once per class, ...
 * and not for each class instance.
 */
class MyClass {

    const A = 1;
    private const B = 2;
 
    public function  __construct() {}
}

echo MyClass::A; // 1






Questions and answers




What is the value?

  • a) 2
  • b) Warning: A already defined

How do you define a class constant?

  • a) constant B = 1;
  • b) const B = 1;

How do you call a class constant named CCC?

  • a) $this->CCC
  • b) self::CCC


References