Php const syntax error

constant

constant() is useful if you need to retrieve the value of a constant, but do not know its name. I.e. it is stored in a variable or returned by a function.

This function works also with class constants and enum cases.

Parameters

Return Values

Returns the value of the constant.

Errors/Exceptions

If the constant is not defined, an Error exception is thrown. Prior to PHP 8.0.0, an E_WARNING level error was generated in that case.

Changelog

Version Description
8.0.0 If the constant is not defined, constant() now throws an Error exception; previously an E_WARNING was generated, and null was returned.

Examples

Example #1 Using constant() with Constants

echo MAXSIZE ;
echo constant ( «MAXSIZE» ); // same thing as the previous line

interface bar const test = ‘foobar!’ ;
>

class foo const test = ‘foobar!’ ;
>

var_dump ( constant ( ‘bar::’ . $const )); // string(7) «foobar!»
var_dump ( constant ( ‘foo::’ . $const )); // string(7) «foobar!»

Example #2 Using constant() with Enum Cases (as of PHP 8.1.0)

enum Suit
case Hearts ;
case Diamonds ;
case Clubs ;
case Spades ;
>

var_dump ( constant ( ‘Suit::’ . $case )); // enum(Suit::Hearts)

See Also

  • define() — Defines a named constant
  • defined() — Checks whether a given named constant exists
  • get_defined_constants() — Returns an associative array with the names of all the constants and their values
  • The section on Constants

User Contributed Notes 17 notes

The constant name can be an empty string.

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)

As of PHP 5.4.6 constant() pays no attention to any namespace aliases that might be defined in the file in which it’s used. I.e. constant() always behaves as if it is called from the global namespace. This means that the following will not work:

Читайте также:  Php string to decimal

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

However, calling constant(‘Foo::BAR’) will work as expected.

It is worth noting, that keyword ‘self’ can be used for constant retrieval from within the class it is defined

class Foo const PARAM_BAR = ‘baz’ ;

public function getConst ( $name ) return constant ( «self:: < $name >» );
>
>

$foo = new Foo ();
echo $foo -> getConst ( ‘PARAM_BAR’ ); // prints ‘baz’
?>

Technically you can define constants with names that are not valid for variables:

// $3some is not a valid variable name
// This will not work
$ 3some = ‘invalid’ ;

// This works
define ( ‘3some’ , ‘valid’ );
echo constant ( ‘3some’ );

?>

Of course this is not a good practice, but PHP has got you covered.

$file_ext is the file Extension of the image

When you often write lines like

if( defined ( ‘FOO’ ) && constant ( ‘FOO’ ) === ‘bar’ )
.
>

?>

to prevent errors, you can use the following function to get the value of a constant.

function getconst ( $const )
return ( defined ( $const )) ? constant ( $const ) : null ;
>

?>

Finally you can check the value with

To access the value of a class constant use the following technique.

In reply to VGR_experts_exchange at edainworks dot com

To check if a constant is boolean, use this instead:

if ( TRACE === true ) <>
?>

Much quicker and cleaner than using defined() and constant() to check for a simple boolean.

IMO, using ($var === true) or ($var === false) instead of ($var) or (!$var) is the best way to check for booleans no matter what. Leaves no chance of ambiguity.

Checking if a constant is empty is bork.

if (empty( B )) // syntax error
if (empty( constant ( ‘B’ ))) // fatal error

// so instead, thanks to LawnGnome on IRC, you can cast the constants to boolean (empty string is false)
if (((boolean) A ) && ((boolean) B ))
// do stuff
?>

Читайте также:  Видоизменение цветовой палитры при помощи css

This function is namespace sensitive when calling class constants.

class foo const BAR = ‘Hello World’ ;
>

constant ( ‘sub\foo::BAR’ ); // works

?>

This does not seem to affect constants defined with the ‘define’ function. Those all end up defined in the root namespace unless another namespace is implicitly defined in the string name of the constant.

define ( __NAMESPACE__ . ‘\Bar’ , ‘its work’ ); // ..but IDE may make notice

You can define values in your config file using the names of your defined constants, e.g.

in your php code:
define(«MY_CONST»,999);

in you config file:
my = MY_CONST

When reading the file do this:

$my = constant($value); // where $value is the string «MY_CONST»

now $my holds the value of 999

Return constants from an object. You can filter by regexp or match by value to find a constant name from the value.

function findConstantsFromObject ( $object , $filter = null , $find_value = null )
$reflect = new ReflectionClass ( $object );
$constants = $reflect -> getConstants ();

class Example
const GENDER_UNKNOW = 0 ;
const GENDER_FEMALE = 1 ;
const GENDER_MALE = 2 ;

const USER_OFFLINE = false ;
const USER_ONLINE = true ;
>

$all = findConstantsFromObject ( ‘Example’ );

$genders = findConstantsFromObject ( ‘Example’ , ‘/^GENDER_/’ );

$my_gender = 1 ;
$gender_name = findConstantsFromObject ( ‘Example’ , ‘/^GENDER_/’ , $my_gender );

if (isset( $gender_name [ 0 ]))
$gender_name = str_replace ( ‘GENDER_’ , » , key ( $gender_name ));
>
else
$gender_name = ‘WTF!’ ;
>

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,

would evaluate to `TRUE` and run anyway. A rather unexpected result.

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.

Читайте также:  SEARCH

The PHP behavior regarding undefined constants is particularly glaring when having a particular constant defined is the exception, «falsey» is the default, and having a «truthy» value exposes a security issue. For example,
.

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)

Источник

Php const syntax error

Выдает такую ошибку изза date(‘t’):

Код:

Parse error: syntax error, unexpected ‘(‘, expecting ‘)’ in D:\. \. php on line 8

Вопрос, как её исправить, чтоб можно было использовать date(‘t’)?

Код:

const USER = Array(«id» => $session->id, «login» => $session->login);

Код:

Parse error: syntax error, unexpected ‘const’ (T_CONST) in D:\. \. php on line 44

Код:

if(true) const USER = Array(«id» => $session->id, «login» => $session->login);

Цитата:

можно краткий пример?)

1) поставить php7
2) использовать вышеупомянутую конструкцию.

Цитата:

if(true) const USER = Array(«id» => $session->id, «login» => $session->login);

я же написал — const используется только в классе для определения констант.

Код:

class Foo <
const var = 1;
>

Цитата:

какую именно? У меня она и так работает

тогда зачем спрашивали о массивах? я писал, что массив через define можно определить только в php7
http://php.net/manual/en/function.define.php

Цитата:

The value of the constant. In PHP 5, value must be a scalar value (integer, float, string, boolean, or NULL). In PHP 7, array values are also accepted.

Цитата:

но нельзя использовать PHP код в константе.

нельзя, что логично.
в классе это нельзя делать не только в константе, но и при инициализации всех переменных класса. Такие вещи делаются в конструкторе.

Цитата:

с чего там должны быть какие то ограничения

Малоли. Вдруг есть что-то такое)
Спасибо за ответы.

P.S. оставлю пример использования define() с массивом (только для PHP7+):

Компьютерный форум Ru.Board » Интернет » Web-программирование » PHP: работа с константами (const)

Реклама на форуме Ru.Board.

Powered by Ikonboard «v2.1.7b» © 2000 Ikonboard.com
Modified by Ru.B0ard
© Ru.B0ard 2000-2023

Источник

Оцените статью