Home  >  Article  >  Backend Development  >  What are php class constants? Detailed explanation of class constant usage

What are php class constants? Detailed explanation of class constant usage

伊谢尔伦
伊谢尔伦Original
2017-06-29 09:10:113883browse

This article mainly introduces the usage of php classconstants. The examples analyze the concepts, characteristics and related usage skills of class constants in php. Friends in need can refer to the examples in this article

Describes the usage of PHP class constants. Share it with everyone for your reference. The details are as follows:

Class constants belong to the class itself, not to object instances, and cannot be accessed through object instances

Subclasses can override constants in parent classes , you can call the constants in the parent class through (parent::)

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

Constant values ​​can only be scalars, string, bool, integer, float, null. You can use the nowdoc structure to initialize constants

<?php
/**
 * PHP类常量
 *
 * 类常量属于类自身,不属于对象实例,不能通过对象实例访问
 * 不能用public,protected,private,static修饰
 * 子类可以重写父类中的常量,可以通过(parent::)来调用父类中的常量
 * 自PHP5.3.0起,可以用一个变量来动态调用类。但该变量的值不能为关键字(如self,parent或static)。
 */
class Foo
{
  // 常量值只能是标量,string,bool,integer,float,null,可以用nowdoc结构来初始化常量
  const BAR = &#39;bar&#39;;
  public static function getConstantValue()
  {
    // 在类的内部可以用self或类名来访问自身的常量,外部需要用类名
    return self::BAR;
  }
  public function getConstant()
  {
    return self::BAR;
  }
}
$foo = &#39;Foo&#39;;
echo $foo::BAR, &#39;<br />&#39;;
echo Foo::BAR, &#39;<br />&#39;;
$obj = new Foo();
echo $obj->getConstant(), &#39;<br />&#39;;
echo $obj->getConstantValue(), &#39;<br />&#39;;
echo Foo::getConstantValue();
// 以上均输出bar
class Bar extends Foo
{
  const BAR = &#39;foo&#39;; // 重写父类常量
  public static function getMyConstant()
  {
    return self::BAR;
  }
  public static function getParentConstant()
  {
    return parent::BAR;
  }
}
echo Bar::getMyConstant(); // foo
echo Bar::getParentConstant(); // bar

The above is the detailed content of What are php class constants? Detailed explanation of class constant usage. For more information, please follow other related articles on the PHP Chinese website!

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