Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

Keyword const

Declare a named constant using a constant expression, without a dollar sign.

Version: PHP 8.4; repository runtime, production runtime not attested

Syntax

const TAX = 2; class Invoice { public const int SCALE = 100; }

Declare a named constant using a constant expression, without a dollar sign. A namespace constant is accessed by name and a class constant through :: with visibility rules. PHP 8.3 added types for class constants. Constants cannot be reassigned like variables. A child may override a non-final constant by redeclaring it with a covariantly narrower type. final forbids this override.

namespace Billing;
const TAX=2; class Invoice { public const int SCALE=100; }
echo TAX*Invoice::SCALE;
class BaseCode {public const int|string CODE="v";final public const int REV=2;} class NumericCode extends BaseCode {public const int CODE=3;} echo "\n",json_encode([BaseCode::CODE,NumericCode::CODE,NumericCode::REV]);
200
["v",3,2]

Examples

<?php
namespace Billing;
const TAX=2; class Invoice { public const int SCALE=100; }
echo TAX*Invoice::SCALE;
class BaseCode {public const int|string CODE="v";final public const int REV=2;} class NumericCode extends BaseCode {public const int CODE=3;} echo "\n",json_encode([BaseCode::CODE,NumericCode::CODE,NumericCode::REV]);

Result

200
["v",3,2]

Sources