亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
1. Visibility of Class Constants
2. Inheritance and Method Resolution
3. Using final to Prevent Constant Override
Practical Tips
Home Backend Development PHP Tutorial Mastering Class Constants: Visibility, Inheritance, and `final` Modifiers

Mastering Class Constants: Visibility, Inheritance, and `final` Modifiers

Aug 01, 2025 am 06:17 AM
PHP Constants

Class constants are public by default and can be controlled with visibility modifiers: 1. public allows access from anywhere, 2. protected restricts access to the class and its subclasses, 3. private limits access to the defining class only; they are inherited but resolution depends on self:: (early binding) or static:: (late static binding), and using final in PHP 8.1 prevents overriding, enhancing class design predictability and maintainability.

Mastering Class Constants: Visibility, Inheritance, and `final` Modifiers

Class constants are a fundamental feature in object-oriented programming, especially in languages like PHP and Java. They allow you to define values that remain unchanged throughout the execution of your program. But to use them effectively, you need to understand how visibility, inheritance, and the final modifier affect their behavior.

Mastering Class Constants: Visibility, Inheritance, and `final` Modifiers

Let’s break down each of these concepts with practical insights.


1. Visibility of Class Constants

By default, class constants are public in most languages (like PHP and Java), meaning they can be accessed from anywhere — inside the class, in child classes, and from outside code.

Mastering Class Constants: Visibility, Inheritance, and `final` Modifiers

In PHP, you can explicitly set visibility:

class MathUtils {
    public const PI = 3.14159;
    protected const MAX_VALUE = 1000;
    private const SECRET = 'hidden';
}
  • public → Accessible everywhere.
  • protected → Only accessible within the class and its subclasses.
  • private → Only accessible within the defining class.

Example:

Mastering Class Constants: Visibility, Inheritance, and `final` Modifiers
class Child extends MathUtils {
    public function showConstants() {
        echo self::PI;        // OK
        echo self::MAX_VALUE; // OK (protected)
        // echo self::SECRET; // Error! (private)
    }
}

? Key Point: Visibility controls who can read the constant. Unlike properties, constants cannot be changed after definition — visibility only restricts access, not mutability.


2. Inheritance and Method Resolution

Class constants are inherited by child classes, just like methods and properties.

class Animal {
    public const SPECIES = 'Unknown';
    public function info() {
        echo static::SPECIES; // Late static binding
    }
}

class Dog extends Animal {
    public const SPECIES = 'Canine';
}

Calling Dog::SPECIES returns 'Canine', overriding the parent.

But here’s where it gets interesting: constant resolution depends on how you reference it.

  • self::CONSTANT → Refers to the constant in the current class (early binding).
  • static::CONSTANT → Uses late static binding, meaning it resolves to the called class (useful in inheritance).

Example:

echo Dog::info(); // Outputs: Canine

Because info() uses static::SPECIES, it refers to Dog’s version, not Animal’s.

?? Watch out: If you use self::SPECIES in the parent method, it would always return 'Unknown', even when called on Dog.


3. Using final to Prevent Constant Override

Sometimes, you want to make sure a constant cannot be redefined in child classes. That’s where the final modifier comes in — at least in PHP 8.1 .

class BankAccount {
    final public const TYPE = 'Standard';
}

class SavingsAccount extends BankAccount {
    // This will cause a Fatal error:
    // public const TYPE = 'Savings'; // ? Cannot override final constant
}

Before PHP 8.1, there was no way to make constants final. Now, you can lock them down.

? Use final on constants when their value is a core part of the class contract and must not change.

Note: Java doesn’t have an exact equivalent because all constants (defined with public static final) are implicitly final — you can’t override them at all. So this behavior varies by language.


Practical Tips

Here are a few best practices when working with class constants:

  • ? Use private constants for internal magic numbers or strings.
  • ? Prefer static:: over self:: when accessing constants in inherited methods.
  • ? Mark critical constants as final (in PHP 8.1 ) to prevent accidental overrides.
  • ? Don’t treat constants like configuration — if values change per environment, use config files or dependency injection.

Basically, class constants aren’t just static values — their behavior changes based on visibility, inheritance rules, and modifiers like final. Understanding these nuances helps you design more predictable and maintainable class hierarchies.

The above is the detailed content of Mastering Class Constants: Visibility, Inheritance, and `final` Modifiers. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
Understanding Constant Expression Evaluation in PHP's Engine Understanding Constant Expression Evaluation in PHP's Engine Jul 29, 2025 am 05:02 AM

PHPevaluatesconstantexpressionsatcompiletimetoimproveperformanceandenableearlyerrordetection.1.Constantexpressionevaluationmeanscomputingvaluesduringcompilationwhenalloperandsareknownconstantslikeliterals,classconstants,orpredefinedconstants.2.PHP’se

Unveiling the Behavior of Constants within PHP Traits and Inheritance Unveiling the Behavior of Constants within PHP Traits and Inheritance Jul 29, 2025 am 03:58 AM

PHPdoesnotallowconstantredeclarationbetweentraitsandclasses,resultinginafatalerrorwhenduplicateconstantnamesoccuracrosstraits,parentclasses,orchildclasses;1)constantsintraitsarecopieddirectlyintotheusingclassatcompiletime;2)ifaclassdefinesaconstantwi

The Performance Paradigm: Analyzing the Speed of Constants vs. Variables The Performance Paradigm: Analyzing the Speed of Constants vs. Variables Jul 30, 2025 am 05:41 AM

?Yes,constantsarefasterthanvariablesincompiledlanguagesduetocompile-timeevaluationandinlining.1.Constantsareevaluatedatcompiletime,enablingvalueinlining,constantfolding,andeliminationofmemoryallocation,whilevariablesrequireruntimeresolutionandmemorya

Architecting with Immutability: Strategic Use of Constants in PHP Architecting with Immutability: Strategic Use of Constants in PHP Jul 29, 2025 am 04:52 AM

ConstantsshouldbeusedtoenforceimmutabilityinPHPforbettercodeclarityandsafety;1)useconstantsforconfigurationanddomainlogiclikestatuscodesorAPIendpointstoavoidmagicvalues;2)preferclassorinterface-scopedconstantsoverglobalonestoimprovenamespacinganddisc

Namespacing and Constants: Avoiding Collisions in Large-Scale Projects Namespacing and Constants: Avoiding Collisions in Large-Scale Projects Jul 30, 2025 am 05:35 AM

Namespacingpreventsconstantcollisionsinlarge-scalesoftwareprojectsbygroupingrelatedconstantswithinuniquescopes.1)Constants,whichshouldremainunchangedduringruntime,cancausenamingconflictswhendefinedglobally,asdifferentmodulesorlibrariesmayusethesamena

`define()` vs. `const`: A Deep Dive into PHP Constant Declaration `define()` vs. `const`: A Deep Dive into PHP Constant Declaration Jul 30, 2025 am 05:02 AM

Use const first because it parses at compile time, has better performance and supports namespaces; 2. When you need to define constants in conditions and functions or use dynamic names, you must use define(); 3. Only const can be used to define constants in classes; 4. define() can dynamically define expressions and complete namespace strings at runtime; 5. Once both are defined, they cannot be modified, but define() can avoid repeated definitions through defined(), while const cannot be checked; 6. The const name must be literal and does not support variable interpolation. Therefore, const is suitable for fixed and explicit constants, define() is suitable for scenarios that require runtime logic or dynamic naming.

Demystifying PHP's Magic Constants for Context-Aware Applications Demystifying PHP's Magic Constants for Context-Aware Applications Jul 30, 2025 am 05:42 AM

The seven magic constants of PHP are __LINE__, __FILE__, __DIR__, __FUNCTION__, __CLASS__, __TRAIT__, __METHOD__, and they can dynamically return code location and context information, 1. LINE returns the current line number, for precise debugging; 2. FILE returns the absolute path of the current file, often used to reliably introduce files or define root directory; 3. DIR returns the directory where the current file is located, which is clearer and more efficient than dirname (__FILE__); 4. FUNCTION returns the current function name, suitable for function-level log tracking; 5. CLASS returns the current class name (including namespace), in logs and factories

Achieving Type Safety with PHP Class Constants and Enumerations Achieving Type Safety with PHP Class Constants and Enumerations Jul 30, 2025 am 01:23 AM

PHP8.1 enumsprovidetruetypesafetyoverclassconstantsbyenablingnativetypehintsandcompile-timevalidation.1.Classconstantslacktypeenforcement,allowinginvalidstringstobepassed.2.Pureandbackedenums(e.g.,enumOrderStatus:string)ensureonlyvalidcasesareaccepte

See all articles