类常量

我们可以在类中定义常量。常量的值将始终保持不变。在定义和使用常量的时候不需要使用$符号。

常量的值必须是一个定值,不能是变量,类属性或其它操作(如函数调用)的结果。

Its also possible for interfaces to have constants. Look at the interface documentation for examples. 接口(interface)中也可以定义常量。请查看接口的文档获得更多示例。

PHP5.3.0之后,我们可以用一个变量来动态调用类。但该变量的值不能为关键字self, parentstatic

Example #1 定义和使用一个类常量

<?php
class MyClass
{
    const 
constant 'constant value';

    function 
showConstant() {
        echo  
self::constant " ";
    }
}

echo 
MyClass::constant " ";

$classname "MyClass";
echo 
$classname::constant " "// PHP 5.3.0之后

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

echo 
$class::constant." "// PHP 5.3.0之后
?>

Example #2 静态数据示例

<?php
class foo {
    
// PHP 5.3.0之后
    
const bar = <<<'EOT'
bar
EOT;
}
?>

和heredocs(字符串边界符)不同,nowdocs可以用在任何静态数据中。

Note:

PHP 5.3.0起PHP支持Nowdoc功能。


PHP MySQL HTML CSS JavaScript MSSQL AJAX .NET JSP Linux Mac ASP 服务器 SQL jQuery C# C++ java Android IOS oracle MongoDB SQLite wamp 交通频道