Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php class constant visibility

Can we set visibility of class constant?
For this example:

class MyClass {     const CONST_VALUE = 'A constant value'; } 

Can we specify

public const CONST_VALUE = 'A constant value'; 

or

private const CONST_VALUE = 'A constant value'; 

or

protected const CONST_VALUE = 'A constant value'; 
like image 651
Poonam Bhatt Avatar asked Mar 17 '11 13:03

Poonam Bhatt


People also ask

Are constants public or private?

Constants are private by default. Within procedures, constants are always private; their visibility can't be changed. In standard modules, the default visibility of module-level constants can be changed by using the Public keyword.

What is class constant in PHP?

PHP - Class ConstantsClass constants can be useful if you need to define some constant data within a class. A class constant is declared inside a class with the const keyword. Class constants are case-sensitive. However, it is recommended to name the constants in all uppercase letters.

When creating a class in PHP the default visibility of a method is?

Default is public. Class methods may be defined as public, private, or protected. Methods declared without any explicit visibility keyword are defined as public.

How do you call a constant in PHP?

A constant is an identifier (name) for a simple value. The value cannot be changed during the script. A valid constant name starts with a letter or underscore (no $ sign before the constant name). Note: Unlike variables, constants are automatically global across the entire script.


2 Answers

Update: visibility modifiers for constants have been added in PHP 7.1 (released 1st of December 2016). See the RFC : Support Class Constant Visibility.

The syntax looks like this:

class ClassName {     private const PRIVATE_CONST = 0;     protected const PROTECTED_CONST = 0;     public const PUBLIC_CONST = 0; } 
like image 72
Morgan Touverey Quilling Avatar answered Sep 23 '22 11:09

Morgan Touverey Quilling


As of PHP7.1 visibility modifiers are allowed for class constants, in previous versions it's not possible to set the visibility of constants in a class. They're always public. See the comments at http://www.php.net/manual/en/language.oop5.constants.php for more information.

like image 21
Alex Avatar answered Sep 25 '22 11:09

Alex