-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path003_class_constant.php
61 lines (47 loc) · 1.68 KB
/
003_class_constant.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<?php
// CONSTANT are attributes that are not expected to change,
// they are hard coded in the code and are imutable the entire life cycle
// of the application,
// Class Constants can be defined on a per class basis
class MyClass
{
const CONSTANT = "constant value";
// constants attributes are not proceeded with a dollar sign
function showConstant()
{
// use the :: to access constant attributes from a class
// notice the use line end character after echoing a value
echo self::CONSTANT . "\n";
}
}
// when accessing the constant use ::
echo MyClass::CONSTANT . "\n";
$classname = "MyClass";
echo $classname::CONSTANT . "\n";
$class = new MyClass();
echo $class::CONSTANT . "\n";
$class->showConstant();
// there is a special constant for all classes called class
// MyClass::class
// this allows for fully qualified class names at compile time
echo MyClass::class . "\n";
// just like regular variables, the class constant can take expressions that are evaluated to a single value
const ONE = 1 * 1;
class SomeClass
{
const TWO = ONE + ONE;
const THREE = self::TWO + ONE;
const SENTENCE = "this is a " . "simple sentence";
}
echo "This is value of SomeClass::TWO: " . SomeClass::TWO . "\n";
echo "This is value of SomeClass::THREE: " . SomeClass::THREE . "\n";
echo "This is value of SomeClass::SENTENCE: " . SomeClass::SENTENCE . "\n";
// visiblity modifers can also be applied to constant this
class Foo {
public const BAR = 'bar';
private const BAZ = 'baz';
}
echo Foo::BAR, PHP_EOL; // notice the use of the PHP_EOL keyword here to replace the . "\n"
// this would fail since it is a private const
// echo Foo::BAZ, PHP_EOL;
?>