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

伊谢尔伦
Release: 2023-03-11 21:38:01
Original
3834 people have browsed it

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 toobjectinstances, 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 orstatic).

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

'; echo Foo::BAR, '
'; $obj = new Foo(); echo $obj->getConstant(), '
'; echo $obj->getConstantValue(), '
'; echo Foo::getConstantValue(); // 以上均输出bar class Bar extends Foo { const BAR = 'foo'; // 重写父类常量 public static function getMyConstant() { return self::BAR; } public static function getParentConstant() { return parent::BAR; } } echo Bar::getMyConstant(); // foo echo Bar::getParentConstant(); // bar
Copy after login

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!

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
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!