search
Homephp教程php手册PHP中如何定义和使用常量

PHP中如何定义和使用常量

Jun 13, 2016 am 11:55 AM
definephpcannotusefunctionbackhowdefinitionconstantcustomize

1.自定义常量

  * 必须用函数define()定义
  * 定义完后其值不能再改变了
  * 使用时直接用常量名,不能像变量一样在前面加$s
 例如:define("PI",3.14);定义一个常量
      $area = PI*R*R; 计算圆的面积
      define("URL","http://www.jb51.net");
      echo "我的网址是:".URL;

2 系统常量:

  FILE :php程序文件名
  LINE :PHP程序文件行数
  PHP_VERSION:当前解析器的版本号
  PHP_OS:执行当前PHP版本的操作系统名称
可以直接拿来使用,例如要查看执行当前PHP版本的操作系统名称,就可以写成 echo PHP_OS

php定义和使用一个类常量

php类常量

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

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

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

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

定义和使用一个类常量

复制代码 代码如下:


class MyClass
{
const constant = ‘constant value';
function showConstant() {
echo self::constant . “\n”;
}
}

echo MyClass::constant . “\n”;

$classname = “MyClass”;
echo $classname::constant . “\n”; // PHP 5.3.0之后

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

echo $class::constant.”\n”; // PHP 5.3.0之后
?>

Example #2 静态数据示例

复制代码 代码如下:


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

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.