PHP 面向对象 PHP5 中的常量
在PHP5中 const定义的常量与定义变量的方法不同,不需要加 $ 修饰符。const PI = 3.14; 这样就可以。
而使用const 定义的常量名称一般都大写,这是一个约定,在任何语言中都是这样。
如果定义的常量由多个单词组成,使用 _ 连接,这也是约定。
比如, MAX_MUMBER 这样的命名方式。一个良好的命名方式,是程序员必须注意的。
类中的常量使用起来类似静态变量,不同点只是它的值不能被改变。我们使用 类名::常量名 来调用这个常量。
复制代码 代码如下:
//声明一个final类Math
class Math{
const PI = 3.14;
public function __toString(){
return "这是Math类。";
}
//这里写了一个算圆面积的方法.使用了Const常量,
//注意使用的方法,类似与静态变量.
public final function areaOfCircular($r){
return $r * $r * self::PI ;
}
public final function max($a,$b){
return $a > $b ? $a : $b ;
}
}
echo Math::PI ;
?>
程序运行结果:
复制代码 代码如下:
3.14
尝试为const定义的常量赋值,将会出现错误。
复制代码 代码如下:
//声明一个final类Math
class Math{
const PI = 3.14;
public function __toString(){
return "这是Math类。";
}
//这里写了一个算圆面积的方法.使用了Const常量,
//注意使用的方法,类似与静态变量.
public final function areaOfCircular($r){
return $r * $r * self::PI ;
}
public final function max($a,$b){
return $a > $b ? $a : $b ;
}
public function setPI($a){
self::PI = 3.1415;
}
}
echo Math::PI ;
?>
程序运行结果:
复制代码 代码如下:
Parse error: parse error in E:\PHPProjects\test.php on line 17

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools