Home >Backend Development >PHP Tutorial >How to use php class constants?

How to use php class constants?

伊谢尔伦
伊谢尔伦Original
2017-06-29 09:14:431530browse

You can define values ​​that remain unchanged in the class as constants. There is no need to use the $ symbol when defining and using constants.

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

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

Since PHP 5.3.0, you can use a variable to dynamically call a class. But the value of this variable cannot be a keyword (such as self, parent or static).

Example #1 Define and use a class constant

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

echo MyClass::constant . "\n";

$classname = "MyClass";
echo $classname::constant . "\n"; // 自 5.3.0 起

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

echo $class::constant."\n"; // 自 PHP 5.3.0 起
?>

Example #2 Static data example

<?php
class foo {
  // 自 PHP 5.3.0 起
  const bar = <<<&#39;EOT&#39;
bar
EOT;
}
?>

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

Note:

Nowdoc support was added in PHP 5.3.0 .

Note: Unlike otherobject-orientedprogramming languages, in PHP, a class cannot use the final modifier for a property variable.
If you want to declare a property as a constant, you can use the const keyword , and there is no need to use a dollar sign as the variable name prefix, nor to use the access permission modifier. Constant means that although the variable can be accessed, the value of the variable cannot be modified. For example, the following code declares the constant attribute con_var:

<?php
class Foo{
 const con_var="常量属性的值不能被修改<br />";
 public function method_a(){
 echo (self::con_var);
 }
}
echo(Foo::con_var);
$myFoo=new Foo();
echo ($myFoo->method_a());
?>

Constant attributes cannot be accessed using objects, but can only be accessed using classes. Within the class body, you can use "self::constant name", and outside the class body, you can use "self::constant name". Use "classname::constname".

The above is the detailed content of How to use php class constants?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn