0
<?php
    const FOOBAR = "Foo"; // Works.
    const FOOBAR = array("Foo", "Bar"); // Doesn't work.  Makes sense.
    const FOOBAR = serialize(array("Foo", "Bar")); // Doesn't work.  Okay.  :\

    define("FOOBAR", serialize(array("Foo", "Bar"))); // Works!  The heck?
 ?>

PHP Parse error: syntax error, unexpected '(', expecting ',' or ';'

Why can constants be set to serialized objects when they're declared with define(), but not with the const keyword? What am I missing here?

(Tested with 5.3.5-1ubuntu7.2.)

Maxpm
  • 24,113
  • 33
  • 111
  • 170
  • 1
    Constant declarations (also the ones in global context) can only be values, not expressions. You are not doing an *assignment* there, you are *declaring*. – mario Aug 19 '11 at 03:33
  • possible duplicate of [define() vs const](http://stackoverflow.com/questions/2447791/define-vs-const) and [Can I use string concatenation to define a class CONST in PHP?](http://stackoverflow.com/questions/2786279/can-i-use-string-concatenation-to-define-a-class-const-in-php) – mario Aug 19 '11 at 03:38

2 Answers2

4

const can only take scalar or non expressions values.

define will take expressions values and that is why define works in your case.

theprogrammer
  • 2,724
  • 1
  • 18
  • 13
2

const is a compile-time action. define is a run-time action. More php machinery including array allocation and space allocation is available at runtime.

A related SO question

Google php const define

for more

Community
  • 1
  • 1
Larry K
  • 47,808
  • 15
  • 87
  • 140