Code idea development for php constant usage

黄舟
Release: 2023-03-15 10:48:02
Original
1564 people have browsed it

In our daily development work, we often encounter programming about constants. Everyone knows that constants can be understood as quantities with constant values. After a constant is defined, it cannot be changed anywhere else in the script. A constant consists of English letters. Underscores are composed of numbers, but numbers cannot be used as the first letter of a constant. Today I will introduce to you the development of PHP constants~

First download the PHP constant usage library we need for this course: http://www.php.cn/xiazai/leiku/620

After the download is completed, find the php class file we need, unzip it to our local directory, and create a new php file!

After completion, we need to call this class in the new php file and instantiate the class:

<?php
include_once "dingyi2.php";//引入类文件

$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();
?>
Copy after login

Run the file and the result will be as shown below:

Code idea development for php constant usage

So regarding the subclass inheriting the parent class, the subclass can rewrite the parent class:

<?php
include_once "dingyi2.php";//引入类文件
$obj = new Bar();          //实例化列

//输出结果
echo $obj->getMyConstant(), &#39;<br />&#39;;// foo
echo $obj->getParentConstant(), &#39;<br />&#39;;// bar
?>
Copy after login

Run this file, and the result will be as shown below:

Code idea development for php constant usage

Note:

1. Class constants belong to the class itself, not to object instances, and cannot be passed Object instance access

2. Cannot be modified with public, protected, private, static

3. Subclasses can override constants in the parent class and call constants in the parent class through (parent::)

4. 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).

The above is the detailed content of Code idea development for php 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
Popular Tutorials
More>
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!