Can constant be array php

PHP doesn’t allow constants to be arrays

If you ever wanted to have a constant containing an array in PHP, you’ll soon notice that the following does not work:

define('MY_CONSTANT', array('value1', 'value2'));

The reason as explained in the PHP language reference is that:

Only scalar data (boolean, integer, float and string) can be contained in constants.

There are three options to come close to a constant containing an array:

Using serialization

Since constants can contain a string, the obvious solution is to transform this array to a string.

Either using the serialize function when defining the constant and the unserialize function before using it:

// Define the constant as a serialized array define('MY_CONSTANT', serialize(array('value1', 'value2'))); // And unserialize it before usage $my_constant = unserialize(MY_CONSTANT);

or encoding the array to a string yourself, using a separator and using the explode function to convert it back to an array:

// Define the constant as a serialized array define('MY_CONSTANT', 'value1,value2'); // And unserialize it before usage $my_constant = explode(',', MY_CONSTANT);

Declaring a static property

As an alternative to a class constant containing an array, you could defined a static property containing the array:

private static $MY_VALUES = array('value1', 'value2');

Of course, it’s not really the same as a constant since the value could be changed so it is less secure than a constant and you should consider making it private or protected.

Using a getter

In order to prevent the static property from being changed, you should make it private and use a public getter e.g.:

private static $MY_VALUES = array('value1', 'value2'); public static function values($index)

Of course with an associative array, it makes more sense.

You can also use a getter together with the serialization solution so that you do not need to unserialize explicitely every time the array is used:

private const $MY_VALUES = serialize(array('value1', 'value2')); public static function values()

Источник

Can constant be array php

It is possible to define constants on a per-class basis remaining the same and unchangeable. The default visibility of class constants is public .

Note:

Class constants can be redefined by a child class. As of PHP 8.1.0, class constants cannot be redefined by a child class if it is defined as final.

It’s also possible for interfaces to have constants . Look at the interface documentation for examples.

It’s possible to reference the class using a variable. The variable’s value can not be a keyword (e.g. self , parent and static ).

Note that class constants are allocated once per class, and not for each class instance.

Example #1 Defining and using a constant

class MyClass
const CONSTANT = ‘constant value’ ;

function showConstant () echo self :: CONSTANT . «\n» ;
>
>

echo MyClass :: CONSTANT . «\n» ;

$classname = «MyClass» ;
echo $classname :: CONSTANT . «\n» ;

$class = new MyClass ();
$class -> showConstant ();

The special ::class constant allows for fully qualified class name resolution at compile time, this is useful for namespaced classes:

Example #2 Namespaced ::class example

Example #3 Class constant expression example

const ONE = 1 ;
class foo const TWO = ONE * 2 ;
const THREE = ONE + self :: TWO ;
const SENTENCE = ‘The value of THREE is ‘ . self :: THREE ;
>
?>

Example #4 Class constant visibility modifiers, as of PHP 7.1.0

class Foo public const BAR = ‘bar’ ;
private const BAZ = ‘baz’ ;
>
echo Foo :: BAR , PHP_EOL ;
echo Foo :: BAZ , PHP_EOL ;
?>

Output of the above example in PHP 7.1:

bar Fatal error: Uncaught Error: Cannot access private const Foo::BAZ in …

Note:

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

User Contributed Notes 12 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’ ;

public static function GetAll ()
$c = get_called_class ();
return «SELECT * FROM `» . $c :: TABLE_NAME . «`» ;
>
>

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:

/**
* Constants that deal only with the database
*/
class DbConstant extends aClassConstant <
protected $host = ‘localhost’ ;
protected $user = ‘user’ ;
protected $password = ‘pass’ ;
protected $database = ‘db’ ;
protected $time ;
function __construct () <
$this -> time = time () + 1 ; // dynamic assignment
>
>
?>

Those aren’t constants, those are properties of the class. Something like «this->time = time()» would even totally defy the purpose of a constant. Constants are supposed to be just that, constant values, on every execution. They are not supposed to change every time a script runs or a class is instantiated.

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

$b = new B ();
echo $b -> my_const_self ? ‘yes’ : ‘no’ ; // output: no
echo $b -> my_const_static ? ‘yes’ : ‘no’ ; // output: yes
?>

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

const BAR = 1 ;
?>

# bar.php
require ‘foo.php’ ;

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

Hi, i would like to point out difference between self::CONST and $this::CONST with extended class.
Let us have class a:

class a <
const CONST_INT = 10 ;

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

public function getThis () return $this :: CONST_INT ;
>
>
?>

And class b (which extends a)

class b extends a const CONST_INT = 20 ;

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

public function getThis () return parent :: getThis ();
>
>
?>

Both classes have same named constant CONST_INT.
When child call method in parent class, there is different output between self and $this usage.

print_r ( $b -> getSelf ()); //10
print_r ( $b -> getThis ()); //20

Источник

PHP Constants

Summary: in this tutorial, you learn about PHP constants and how to use the define() function and const keyword to define constants.

Introduction to PHP constants

A constant is simply a name that holds a single value. As its name implies, the value of a constant cannot be changed during the execution of the PHP script.

To define a constant, you use the define() function. The define() function takes the constant’s name as the first argument and the constant value as the second argument. For example:

 define('WIDTH','1140px'); echo WIDTH;Code language: PHP (php)

By convention, constant names are uppercase. Unlike a variable, the constant name doesn’t start with the dollar sign( $ ).

By default, constant names are case-sensitive. It means that WIDTH and width are different constants.

It’s possible to define case-insensitive constants. However, it’s deprecated since PHP 7.3

In PHP 5, a constant can hold a simple value like a number, a string, a boolean value. From PHP 7.0, a constant can hold an array. For example:

 define( 'ORIGIN', [0, 0] );Code language: PHP (php)

Like superglobal variables, you can access constants from anywhere in the script.

The const keyword

PHP provides you with another way to define a constant via the const keyword. Here’s the syntax:

const CONSTANT_NAME = value;Code language: PHP (php)

In this syntax, you define the constant name after the const keyword. To assign a value to a constant, you use the assignment operator (=) and the constant value. The constant value can be scalar, e.g., a number, a string, or an array.

The following example uses the const keyword to define the SALES_TAX constant:

 const SALES_TAX = 0.085; $gross_price = 100; $net_price = $gross_price * (1 + SALES_TAX); echo $net_price; // 108.5Code language: PHP (php)

The following example uses the const keyword to define the RGB constant that holds an array:

 const RGB = ['red', 'green', 'blue'];Code language: PHP (php)

define vs const

First, the define() is a function while the const is a language construct.

It means that the define() function defines a constant at run-time, whereas the const keyword defines a constant at compile time.

In other words, you can use the define() function to define a constant conditionally like this:

 if(condition) < define('WIDTH', '1140px'); >Code language: PHP (php)

However, you cannot use the const keyword to define a constant this way. For example, the syntax of the following code is invalid:

 if(condition) < const WIDTH = '1140px'; >Code language: PHP (php)

Second, the define() function allows you to define a constant with the name that comes from an expression. For example, the following defines three constants OPTION_1 , OPTION_2 , and OPTION_3 with the values 1, 2, and 3.

 define('PREFIX', 'OPTION'); define(PREFIX . '_1', 1); define(PREFIX . '_2', 2); define(PREFIX . '_3', 3);Code language: PHP (php)

However, you cannot use the const keyword to define a constant name derived from an expression.

Unless you want to define a constant conditionally or use an expression, you can use the const keyword to define constants to make the code more clear.

Note that you can use the const keyword to define constants inside classes.

Summary

  • A constant is a name that holds a simple value that cannot be changed during the execution of the script. From PHP 7, a constant can hold an array.
  • A constant can be accessed from anywhere in the script.
  • Use the define() function or const keyword to define a constant.
  • Use the define() function if you want to define a constant conditionally or using an expression.

Источник

Читайте также:  Php merge array key and value
Оцените статью