Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - use array as class constant [duplicate]

Possible Duplicate:
Is it possible to declare an array as constant

Is it possible to use an array as a class constant in PHP?

I.e

const MYARRAY = array('123', '234'); 

If not why?

like image 282
Martin Avatar asked Jun 25 '12 06:06

Martin


People also ask

Can an array be a class constant?

No, you can't. But you could declare it as a static property. Array const is available from PHP 5.6. @Martin Yep, that's true, but you can not declare a constant with an array.

Can an array be a const PHP?

Yes, You can define an array as constant. From PHP 5.6 onwards, it is possible to define a constant as a scalar expression, and it is also possible to define an array constant. It is possible to define constants as a resource, but it should be avoided, as it can cause unexpected results.

Can you redefine constants in PHP?

No, you cannot redefine a constant (except with runkit_constant_redefine), that's why is called CONSTANT.

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

No, you can't.

But you could declare it as a static property.

public static $MYARRAY = array('123', '234'); 

---------------Update-----------------------------

Array const is available from PHP 5.6.

php.net/manual/en/migration56.new-features.php

like image 70
xdazz Avatar answered Sep 28 '22 04:09

xdazz


UPDATE:

This is now available in PHP 5.6 https://php.net/manual/en/migration56.new-features.php


No you can't assign an Array to PHP constant.

In http://www.php.net/manual/en/language.constants.syntax.php

Constants may only evaluate to scalar values

This is the reason.

Scalar values for examples are int, float, string

like image 42
Alvin Wong Avatar answered Sep 28 '22 05:09

Alvin Wong