Details of the use of php class constants

  • 2020-06-07 04:07:41
  • OfStack

Values that remain constant in a class can be defined as constants. You do not need to use the $symbol when defining and using constants.

The value of a constant must be a fixed value, not a variable, class attribute, result of a mathematical operation, or function call.

Constants can also be defined in interfaces (interface). See the interface section of the documentation for more examples.

Starting with PHP 5.3.0, classes can be invoked dynamically with a variable. But the value of this variable cannot be a keyword (such as self, parent, or static).

Example #1 defines and USES 1 class constant


<?php
class MyClass
{
  const constant = 'constant value';
  function showConstant() {
    echo self::constant . "\n";
  }
}

echo MyClass::constant . "\n";

$classname = "MyClass";
echo $classname::constant . "\n"; //  Since the  5.3.0  since 

$class = new MyClass();
$class->showConstant();

echo $class::constant."\n"; //  Since the  PHP 5.3.0  since 
?>

Example #2 static data example


<?php
class foo {
  //  Since the  PHP 5.3.0  since 
  const bar = <<<'EOT'
bar
EOT;
}
?>

Unlike heredoc, nowdoc can be used with any static data.

Note:

Nowdoc support was added to PHP 5.3.0.

More can refer to this article: http: / / php net manual/zh/language oop5. constants. # php language. oop5. constants

Note: In php, unlike other object-oriented programming languages, classes cannot use the final modifier on an attribute variable.
If you want to declare a property as a constant, you can use the const keyword without prefixing the variable name with a dollar sign or access modifier. A constant means that the variable can be accessed, but its value cannot be modified. For example, the following code declares the constant attribute con_var:


<?php
class Foo{
 const con_var=" The value of the constant property cannot be modified <br />";
 public function method_a(){
 echo (self::con_var);
 }
}
echo(Foo::con_var);
$myFoo=new Foo();
echo ($myFoo->method_a());
?>

Constant properties cannot be accessed by objects, only by classes. In the body of the class, you can use "self:: constant name", and outside of the class ontology, you can use "class name :: constant name".


Related articles: