php const in class

Константы

Содержание

Имя константы должно соответствовать тем же правилам именования, что и другие имена в PHP. Правильное имя начинается с буквы или символа подчёркивания, за которым следует любое количество букв, цифр и символов подчёркивания. Регулярное выражение для проверки правильности имени константы выглядит так: ^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$

Пример #1 Правильные и неправильные имена констант

Как и superglobals, константы доступны из любой области видимости. Константы можно использовать из любого места скрипта независимо от области видимости. Подробную информацию об областях видимости можно найти здесь.

Замечание: Начиная с PHP 7.1.0, константе класса можно объявлять видимость защищённая или закрытая, делая её доступной только в иерархической области видимости класса, в котором она определена.

User Contributed Notes 14 notes

CONSTANTS and PHP Class Definitions

public static function getMinValue ()
<
return self :: MIN_VALUE ;
>

public static function getMaxValue ()
<
return self :: MAX_VALUE ;
>
>

?>

#Example 1:
You can access these constants DIRECTLY like so:
* type the class name exactly.
* type two (2) colons.
* type the const name exactly.

#Example 2:
Because our class definition provides two (2) static functions, you can also access them like so:
* type the class name exactly.
* type two (2) colons.
* type the function name exactly (with the parentheses).

#Example 1:
$min = Constants :: MIN_VALUE ;
$max = Constants :: MAX_VALUE ;

#Example 2:
$min = Constants :: getMinValue ();
$max = Constants :: getMaxValue ();

The documentation says, «You can access constants anywhere in your script without regard to scope», but it’s worth keeping in mind that a const declaration must appear in the source file before the place where it’s used.

This is potentially confusing because you can refer to a function that occurs later in your source file, but not a constant. Even though the const declaration is processed at compile time, it behaves a bit like it’s being processed at run time.

I find using the concatenation operator helps disambiguate value assignments with constants. For example, setting constants in a global configuration file:

class constant are by default public in nature but they cannot be assigned visibility factor and in turn gives syntax error

const MAX_VALUE = 10 ;
public const MIN_VALUE = 1 ;

// This will work
echo constants :: MAX_VALUE ;

// This will return syntax error
echo constants :: MIN_VALUE ;
?>

Lets expand comment of ‘storm’ about usage of undefined constants. His claim that ‘An undefined constant evaluates as true. ‘ is wrong and right at same time. As said further in documentation ‘ If you use an undefined constant, PHP assumes that you mean the name of the constant itself, just as if you called it as a string. ‘. So yeah, undefined global constant when accessed directly will be resolved as string equal to name of sought constant (as thought PHP supposes that programmer had forgot apostrophes and autofixes it) and non-zero non-empty string converts to True.

Warning, constants used within the heredoc syntax (http://www.php.net/manual/en/language.types.string.php) are not interpreted!

Editor’s Note: This is true. PHP has no way of recognizing the constant from any other string of characters within the heredoc block.

//Syntax of define constant in php
//define(name, value, case-insensitive);

//results of all are the same
echo ‘
‘ ;
echo BOOK ;
echo ‘
‘ ;
echo book ;

define(‘MYKEY’, ‘The value is from outside of class’);
class Abc<

$obj = new Abc(); // define function will call
$obj->getOutput(); // hello world! The value is from outside of class

echo TEST; // hello world! Because the constants is defined while constructor call

An undefined constant evaluates as true when not used correctly. Say for example you had something like this:

if ( DEBUG ) <
// echo some sensitive data.
>
?>

If for some reason settings.php doesn’t get included and the DEBUG constant is not set, PHP will STILL print the sensitive data. The solution is to evaluate it. Like so:

if ( DEBUG == 1 ) <
// echo some sensitive data.
>
?>

Now it works correctly.

Performance of constants. PHP 7.1.10 32 bits (Opcache active, windows 10 i7-64bits) but apparently the trends is the same with the 5.x

In average, the use of DEFINE and CONST is around the same with some sightly better performance of CONST instead of DEFINE. However, using a variable is around 10-50% better than to use a constant. So, for a performance intensive task, constant is not the best option.

echo constant ( ‘echo’ ); // outputs ‘My constant value’
?>

When we start a constant name with space, it doesn’t produce any error.

But when we call this constant, it produce error.

Источник

How can I define a constant inside a class, and make it so it’s visible only when called in a class context?

. something like Foo::app()->MYCONSTANT;

(and if called like MYCONSTANT to be ignored)

5 Answers 5

This is and old question, but now on PHP 7.1 you can define constant visibility.

EXAMPLE

Output of the above example in PHP 7.1:

Note: As of PHP 7.1.0 visibility modifiers are allowed for class constants.

php const in class. Смотреть фото php const in class. Смотреть картинку php const in class. Картинка про php const in class. Фото php const in class

This is a pretty old question, but perhaps this answer can still help someone else.

You can emulate a public constant that is restricted within a class scope by applying the final keyword to a method that returns a pre-defined value, like this:

The final keyword on a method prevents an extending class from re-defining the method. You can also place the final keyword in front of the class declaration, in which case the keyword prevents class Inheritance.

To get nearly exactly what Alex was looking for the following code can be used:

The emulated constant value would be accessible like this:

You can also create this static function in your parent class and simply inherit this parent class on all other classes to make it a default functionality.

Not the answer you’re looking for? Browse other questions tagged php class constants or ask your own question.

Linked

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Php const in class

Константы класса могут быть переопределены дочерним классом.

Обратите внимание, что константы класса задаются один раз для всего класса, а не отдельно для каждого созданного объекта этого класса.

Пример #1 Объявление и использование константы

class MyClass
<
const CONSTANT = ‘значение константы’ ;

Пример #2 Пример использования ::class с пространством имён

namespace foo <
class bar <
>

echo bar ::class; // foo\bar
>
?>

Пример #3 Пример констант, заданных выражением

Пример #4 Модификаторы видимости констант класса, начиная с PHP 7.1.0

Результат выполнения данного примера в PHP 7.1:

Начиная с PHP 7.1.0 для констант класса можно использовать модификаторы области видимости.

User Contributed Notes 21 notes

it’s possible to declare constant in base class, and override it in child, and access to correct value of the const from the static method is possible by ‘get_called_class’ method:
abstract class dbObject
<
const TABLE_NAME = ‘undefined’ ;

class dbPerson extends dbObject
<
const TABLE_NAME = ‘persons’ ;
>

class dbAdmin extends dbPerson
<
const TABLE_NAME = ‘admins’ ;
>

echo dbPerson :: GetAll (). «
» ; //output: «SELECT * FROM `persons`»
echo dbAdmin :: GetAll (). «
» ; //output: «SELECT * FROM `admins`»

As of PHP 5.6 you can finally define constant using math expressions, like this one:

class MyTimer <
const SEC_PER_DAY = 60 * 60 * 24 ;
>

Most people miss the point in declaring constants and confuse then things by trying to declare things like functions or arrays as constants. What happens next is to try things that are more complicated then necessary and sometimes lead to bad coding practices. Let me explain.

A constant is a name for a value (but it’s NOT a variable), that usually will be replaced in the code while it gets COMPILED and NOT at runtime.

So returned values from functions can’t be used, because they will return a value only at runtime.

Arrays can’t be used, because they are data structures that exist at runtime.

One main purpose of declaring a constant is usually using a value in your code, that you can replace easily in one place without looking for all the occurences. Another is, to avoid mistakes.

Think about some examples written by some before me:

1. const MY_ARR = «return array(\»A\», \»B\», \»C\», \»D\»);»;
It was said, this would declare an array that can be used with eval. WRONG! This is just a string as constant, NOT an array. Does it make sense if it would be possible to declare an array as constant? Probably not. Instead declare the values of the array as constants and make an array variable.

2. const magic_quotes = (bool)get_magic_quotes_gpc();
This can’t work, of course. And it doesn’t make sense either. The function already returns the value, there is no purpose in declaring a constant for the same thing.

3. Someone spoke about «dynamic» assignments to constants. What? There are no dynamic assignments to constants, runtime assignments work _only_ with variables. Let’s take the proposed example:

Conclusion: Don’t try to reinvent constants as variables. If constants don’t work, just use variables. Then you don’t need to reinvent methods to achieve things for what is already there.

I think it’s useful if we draw some attention to late static binding here:
class A <
const MY_CONST = false ;
public function my_const_self () <
return self :: MY_CONST ;
>
public function my_const_static () <
return static:: MY_CONST ;
>
>

class B extends A <
const MY_CONST = true ;
>

const can also be used directly in namespaces, a feature never explicitly stated in the documentation.

# foo.php
namespace Foo ;

const BAR = 1 ;
?>

# bar.php
require ‘foo.php’ ;

var_dump ( Foo \ BAR ); // => int(1)
?>

class a <
const CONST_INT = 10 ;

public function getSelf () <
return self :: CONST_INT ;
>

class b extends a <
const CONST_INT = 20 ;

public function getSelf () <
return parent :: getSelf ();
>

Источник

Константы в PHP — const и define()

Объявлять константы в PHP можно двумя способами:

У каждого способа есть свои особенности, чтобы их понять, давайте рассмотрим все поэтапно, как и что менялось с каждой версией PHP.

Как создавать константы

PHP меньше 5.3

С версии PHP 5.3

Появилось ключевое слово const и теперь константу можно определять еще и с помощью него.

Однако, в const нельзя указать переменную, функцию или какое то выражение, а нужно передавать скаляр «напрямую»:

Тогда как для define() таких ограничений нет.

PHP 5.6

Стало возможным указывать в значения const примитивные PHP выражения (выражения из скаляров):

Стало возможным хранить массивы в константах:

Разница между define() и const

#1 const должны быть объявлены в верхней области

Потому что они определяются при компилировании скрипта. Это значит, что const нельзя использовать внутри функций/циклов/выражений if или try/catch блоков.

#2 const всегда регистрозависима

В то время как define() позволяет создать регистро-независимые константы:

#3 const понимает только скаляры

const нельзя передать переменные, функции, выражения, а define() можно:

С версии PHP 5.6 в const также можно указывать примитивные выражения, а не только скаляры.

#4 const может хранить массивы с версии PHP 5.6, а define с PHP 7.0

Итоги сравнения

Константы PHP класса

Объявленная константа принадлежит именно классу, она не принадлежит ни одному объекту и является общей на всех объектов (экземпляров) класса.

Константы для классов чем-то похожи на статические (static) свойства класса. Не углубляясь в подробности, разница в том, что константу нельзя изменить.

«Волшебные» константы

И в заключении вспомним про особые константы PHP.

В PHP есть девять волшебных констант, которые меняют свое значение в зависимости от контекста, в котором они используются. Например, значение __LINE__ зависит от строки в скрипте, на которой эта константа указана. Все «волшебные» константы разрешаются во время компиляции, в отличии от обычных констант, которые разрешаются во время исполнения. Специальные константы нечувствительны к регистру и их список приведен ниже:

Источник

constant

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

constant — Возвращает значение константы

Описание

Функция constant() полезна, если вам необходимо получить значение константы, но неизвестно её имя. Например, если оно хранится в переменной или возвращается функцией.

Данная функция также работает с константами классов.

Список параметров

Возвращаемые значения

Ошибки

Примеры

Пример #1 Пример функции constant()

echo MAXSIZE ;
echo constant ( «MAXSIZE» ); // результат аналогичен предыдущему выводу

interface bar <
const test = ‘foobar!’ ;
>

class foo <
const test = ‘foobar!’ ;
>

Смотрите также

User Contributed Notes 18 notes

The constant name can be an empty string.

define(«», «foo»);
echo constant(«»);

If you are referencing class constant (either using namespaces or not, because one day you may want to start using them), you’ll have the least headaches when doing it like this:

class Foo <
const BAR = 42 ;
>
?>
namespace Baz ;
use \ Foo as F ;

echo constant ( F ::class. ‘::BAR’ );
?>

since F::class will be dereferenced to whatever namespace shortcuts you are using (and those are way easier to refactor for IDE than just plain strings with hardcoded namespaces in string literals)

The use of constant() (or some other method) to ensure the your_constant was defined is particularly important when it is to be defined as either `true` or `false`.

If `BOO` did NOT get defined as a constant, for some reason,

The reason is that PHP ASSUMES you «forgot» quotation marks around `BOO` when it did not see it in its list of defined constants.
So it evaluates: `if (‘BOO’)`.
Since every string, other than the empty string, is «truthy», the expression evaluates to `true` and the do_something() is run, unexpectedly.

then if `BOO` has not been defined, `constant(BOO)` evaluates to `null`,
which is falsey, and `if (null)`. becomes `false`, so do_something() is skipped, as expected.

Note that only the version using `defined()` works without also throwing a PHP Warning «error message.»

(disclosure: I also submitted an answer to the SO question linked to above)

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *