Home >Backend Development >PHP Tutorial >php class constants

php class constants

伊谢尔伦
伊谢尔伦Original
2016-11-23 14:21:471127browse

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.

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

Example #1 Define and use a class constant

class MyClass
{    const constant = 1;
    function showConstant(){
        echo self::constant.&#39;<br>&#39;;
    }
}
echo MyClass::constant.&#39;<br>&#39;;
$className = "MyClass";
echo $className::constant.&#39;<br>&#39;; //自PHP5.3.0起
$class = new MyClass();
$class -> showConstant();
echo $class::constant.&#39;<br>&#39;;

Example #2 Static data example

class foo{
    const bar = <<<&#39;EOT&#39;
        bar
EOT;
}

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


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