Php const syntax error



Constants

Table of Contents

A constant is an identifier (name) for a simple value. As the name suggests, that value cannot change during the execution of the script (except for magic constants, which aren’t actually constants). Constants are case-sensitive. By convention, constant identifiers are always uppercase.

Prior to PHP 8.0.0, constants defined using the define() function may be case-insensitive.

The name of a constant follows the same rules as any label in PHP. A valid constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thusly: ^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$

It is possible to define() constants with reserved or even invalid names, whose value can only be retrieved with the constant() function. However, doing so is not recommended.

Example #1 Valid and invalid constant names

// Valid constant names
define ( «FOO» , «something» );
define ( «FOO2» , «something else» );
define ( «FOO_BAR» , «something more» );

// Invalid constant names
define ( «2FOO» , «something» );

// This is valid, but should be avoided:
// PHP may one day provide a magical constant
// that will break your script
define ( «__FOO__» , «something» );

Note: For our purposes here, a letter is a-z, A-Z, and the ASCII characters from 128 through 255 (0x80-0xff).

Like superglobals, the scope of a constant is global. Constants can be accessed from anywhere in a script without regard to scope. For more information on scope, read the manual section on variable scope.

Note: As of PHP 7.1.0, class constant may declare a visibility of protected or private, making them only available in the hierarchical scope of the class in which it is defined.

User Contributed Notes 13 notes

11/14/2016 — note updated by sobak
——

CONSTANTS and PHP Class Definitions

Using «define(‘MY_VAR’, ‘default value’)» INSIDE a class definition does not work as expected. You have to use the PHP keyword ‘const’ and initialize it with a scalar value — boolean, int, float, string (or array in PHP 5.6+) — right away.

( ‘MIN_VALUE’ , ‘0.0’ ); // RIGHT — Works OUTSIDE of a class definition.
define ( ‘MAX_VALUE’ , ‘1.0’ ); // RIGHT — Works OUTSIDE of a class definition.

//const MIN_VALUE = 0.0; RIGHT — Works both INSIDE and OUTSIDE of a class definition.
//const MAX_VALUE = 1.0; RIGHT — Works both INSIDE and OUTSIDE of a class definition.

class Constants
<
//define(‘MIN_VALUE’, ‘0.0’); WRONG — Works OUTSIDE of a class definition.
//define(‘MAX_VALUE’, ‘1.0’); WRONG — Works OUTSIDE of a class definition.

const MIN_VALUE = 0.0 ; // RIGHT — Works INSIDE of a class definition.
const MAX_VALUE = 1.0 ; // RIGHT — Works INSIDE of a class definition.

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 ();

?>

Once class constants are declared AND initialized, they cannot be set to different values — that is why there are no setMinValue() and setMaxValue() functions in the class definition — which means they are READ-ONLY and STATIC (shared by all instances of the class).

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 doesn’t work (using PHP 5.4):
();
const X = 1 ;
function foo () <
echo «Value of X: » . X ;
>
?>
Result: «Value of X: X»

But this works:
const X = 1 ;
foo ();
function foo () <
echo «Value of X: » . X ;
>
?>
Result: «Value of X: 1»

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:

( ‘LOCATOR’ , «/locator» );
define ( ‘CLASSES’ , LOCATOR . «/code/classes» );
define ( ‘FUNCTIONS’ , LOCATOR . «/code/functions» );
define ( ‘USERDIR’ , LOCATOR . «/user» );
?>

Later, I can use the same convention when invoking a constant’s value for static constructs such as require() calls:

require_once( FUNCTIONS . «/database.fnc» );
require_once( FUNCTIONS . «/randchar.fnc» );
?>

as well as dynamic constructs, typical of value assignment to variables:

Читайте также:  Goslate python error 429

= randchar ( 8 , ‘anc’ , ‘u’ );
$usermap = USERDIR . «/» . $userid . «.png» ;
?>

The above convention works for me, and helps produce self-documenting code.

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.

There are two ways to prevent this:
1. always use function constant(‘CONST_NAME’) to get constant value (BTW it also works for class constants — constant(‘CLASS_NAME::CONST_NAME’) );
2. use only class constants (that are defined inside of class using keyword const) because they are not converted to string when not found but throw exception instead (Fatal error: Undefined class constant).

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.

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 ;
?>

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

settings.php
// Debug mode
define ( ‘DEBUG’ , false );
?>

test.php
include( ‘settings.php’ );

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:

settings.php
// Debug mode
define ( ‘DEBUG’ , 0 );
?>

test.php
include( ‘settings.php’ );

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

using a constant declared by DEFINE(‘CNS’,value) : 0.63575601577759s
using a constant declared by const CNS=value : 0.61372208595276s
using a variable declared by $v=value : 0.51184010505676s

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.

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

public function __construct() <
define(‘TEST’, ‘hello world! ‘); // using define function in class constructor
>
public function getOutput() <
echo TEST . MYKEY . PHP_EOL; // accessing constants from outside of class
>
>

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

echo Abc::MAX . PHP_EOL; // 10 — accessing constant using scope resolution

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

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

//it will print 100 in output
define ( ‘BOOK’ , 100 );
echo BOOK ;

//it will print 200 in output
define ( ‘book’ , 200 , true );
echo book ;

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

It is perfectly valid to use a built-in PHP keyword as a constant name — as long as you the constant() function to retrieve it later:

( ‘echo’ , ‘My constant value’ );

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

Источник

Php const syntax error

Constants can be defined using the const keyword, or by using the define() -function. While define() allows a constant to be defined to an arbitrary expression, the const keyword has restrictions as outlined in the next paragraph. Once a constant is defined, it can never be changed or undefined.

When using the const keyword, only scalar ( bool , int , float and string ) expressions and constant array s containing only scalar expressions are accepted. It is possible to define constants as a resource , but it should be avoided, as it can cause unexpected results.

The value of a constant is accessed simply by specifying its name. Unlike variables, a constant is not prepended with a $ . It is also possible to use the constant() function to read a constant’s value if the constant’s name is obtained dynamically. Use get_defined_constants() to get a list of all defined constants.

Note: Constants and (global) variables are in a different namespace. This implies that for example true and $TRUE are generally different.

If an undefined constant is used an Error is thrown. Prior to PHP 8.0.0, undefined constants would be interpreted as a bare word string , i.e. (CONSTANT vs «CONSTANT»). This fallback is deprecated as of PHP 7.2.0, and an error of level E_WARNING is issued when it happens. Prior to PHP 7.2.0, an error of level E_NOTICE has been issued instead. See also the manual entry on why $foo[bar] is wrong (unless bar is a constant). This does not apply to (fully) qualified constants, which will always raise a Error if undefined.

Note: To check if a constant is set, use the defined() function.

These are the differences between constants and variables:

  • Constants do not have a dollar sign ( $ ) before them;
  • Constants may be defined and accessed anywhere without regard to variable scoping rules;
  • Constants may not be redefined or undefined once they have been set; and
  • Constants may only evaluate to scalar values or arrays.
Читайте также:  Unknown error code 10060 openvpn

Example #1 Defining Constants

Example #2 Defining Constants using the const keyword

// Simple scalar value
const CONSTANT = ‘Hello World’ ;

// Scalar expression
const ANOTHER_CONST = CONSTANT . ‘; Goodbye World’ ;
echo ANOTHER_CONST ;

const ANIMALS = array( ‘dog’ , ‘cat’ , ‘bird’ );
echo ANIMALS [ 1 ]; // outputs «cat»

// Constant arrays
define ( ‘ANIMALS’ , array(
‘dog’ ,
‘cat’ ,
‘bird’
));
echo ANIMALS [ 1 ]; // outputs «cat»
?>

As opposed to defining constants using define() , constants defined using the const keyword must be declared at the top-level scope because they are defined at compile-time. This means that they cannot be declared inside functions, loops, if statements or try / catch blocks.

See Also

User Contributed Notes 6 notes

the documentation doesn’t go too far in explaining the crucial difference between the two ways of declaring constants in PHP.

Const is handled at compile time, define() at run time. For this reason, a constant cannot be conditionally defined using Const, for example.

Another difference we can notice occurs in the constant declarations in classes. Const infiltrates the class scope, while define() leaks into the global scope.

Class Myclass () <
const NAME = «Nicolas» ;
>

?>

The NAME constant is within the scope of the MyClass class.

Just a quick note:
From PHP7 on you can even define a multidimensional Array as Constant:

Источник

constant

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

constant — Returns the value of a constant

Description

Return the value of the constant indicated by name .

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.

Parameters

The constant name.

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 constant() example

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!»

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.

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)

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:

class Foo <
const BAR = 42 ;
>
?>

namespace Baz ;

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.

Maybe this is useful:

$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.

class a <
const b = ‘c’ ;
>

echo constant ( ‘a::b’ );

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.

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

echo Bar ; // its work

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
?>

This function is namespace sensitive when calling class constants.

Using:
namespace sub ;

class foo <
const BAR = ‘Hello World’ ;
>

constant ( ‘foo::BAR’ ); // Error

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.

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.

Pretty useful sometimes.

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,

if( BOO ) do_something (); ?>

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.

If you instead use:
if ( constant ( BOO )) do_something () ?>

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.

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,
if ( IS_SPECIAL_CASE ) show_php_info () ?> .

There are other ways around this PHP behavior, such as
if ( BOO === true ) do_something (); ?>
or
if ( defined ( ‘BOO’ ) && BOO ) do_something () ?> .

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)

Источник

Оцените статью
toolgir.ru
Adblock
detector