xxxxxxxxxx
<?php
define('CONSTANT', 'Hello world !');
const CONSTANT = 'Hello world !';
const NEW_CONSTANT = CONSTANT.' And beyond...';
const ANIMALS = array('dog', 'cat', 'ant');
define('ANIMALS', array('dog', 'cat', 'ant'));
?>
xxxxxxxxxx
<?php
const Hello = 'Hello world!';
const CONST_ARR = array('div', 'mul', 'sum', 'sub');
define('Const_Arr_Math', array('div', 'mul', 'sum', 'sub'));
define("emp_name","Kumar D");
echo constant("emp_name");
echo PHP_EOL;
echo emp_name;
echo PHP_EOL;
echo Hello;
echo PHP_EOL;
print_r(CONST_ARR);
?>
What is difference between const and define?
1] const defines a constant in the current namespace, while define() has to be passed the full namespace name:
2] As consts are language constructs and defined at compile time they are a bit faster than define()s.
3] define()s are slow when using a large number of constants.
Unless you need any type of conditional or expressional definition, use consts instead of define()s
xxxxxxxxxx
<?php
const Hello = 'Hello world!';
const CONST_ARR = array('div', 'mul', 'sum', 'sub');
define('Const_Arr_Math', array('div', 'mul', 'sum', 'sub'));
define("emp_name","Kumar D");
echo constant("emp_name");
echo PHP_EOL;
echo emp_name;
echo PHP_EOL;
echo Hello;
echo PHP_EOL;
print_r(CONST_ARR);
?>
xxxxxxxxxx
<?php
class MyClass
{
const CONSTANT = 'constant value';
function showConstant() {
echo self::CONSTANT . "\n";
}
}
echo MyClass::CONSTANT . "\n";
$classname = "MyClass";
echo $classname::CONSTANT . "\n";
$class = new MyClass();
$class->showConstant();
echo $class::CONSTANT."\n";
?>
xxxxxxxxxx
class Human {
const TYPE_MALE = 'm';
const TYPE_FEMALE = 'f';
const TYPE_UNKNOWN = 'u'; // When user didn't select his gender
.
}
xxxxxxxxxx
//variable string
$sigla = 'HBG';
//create and reference class constant
$first_sheet = constant('self::' . $sigla . '_FIRST_SHEET');