php class constants

伊谢尔伦
Release: 2016-11-23 14:21:47
Original
1087 people have browsed it

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;;
Copy after login

Example #2 Static data example

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

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


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!