-2

I'm rewriting a C code into PHP (or rather trying) but I've stumbled upon a constant declaration:

C syntax:

const char* translation = "5z]&gqtyfr$";

PHP syntax:

define('translation','5z]&gqtyfr$');

Problem is PHP does not accept constant values to start off with a non-alpha character as far as I know. Any workarounds?

  • 3
    The constant *name* can't start with a non-alpha character. I am not aware of any such restriction on the value. – Sammitch Sep 06 '13 at 21:08
  • What error did you get when you tried this? – Greg Hewgill Sep 06 '13 at 21:09
  • PHP should be fine with any constant value - do you get an error with what you've posted. – halfer Sep 06 '13 at 21:09
  • Of course, it's possible to use such values ([demo](http://codepad.org/b2asHpMV)); why should we use constants if not for storing _arbitrary_ values in them? – raina77ow Sep 06 '13 at 21:09
  • I've not executed anything so far since I barely started writing it but my question is answered now that I've read the comments. Thanks. – Lester Gifness Sep 06 '13 at 21:11

1 Answers1

0

As I was working with c a long time ago, I remember const is scope related definition, a named memory allocation - so it depends where it is defined like inside a function or in global scope etc, and although its value cannot be changed directly, it can be still changed using its memory address.
This cannot be implement in php.

What are constants in PHP is more or like what #define does in C (except you cannot create a macro in PHP)

#define translation = "5z]&gqtyfr$";

is equivalent of php define('translation','5z]&gqtyfr$').

Class constants in php are scope related which works the same way as in most C-like languages that support OOP.

class MyClass {
    const CONST_VALUE = 5;
}
echo MyClass::CONST_VALUE;

Here is some more on "static const" vs "#define" vs "enum"

With php define() you can create constant with any kind of name (as long its not been defined before)

define(' not a good name for constant!', 3);
echo constant(' not a good name for constant!'); // echoes 3

While doing that you obviously cannot call that kind of constants without using constant() function

Community
  • 1
  • 1
Ivan Hušnjak
  • 3,493
  • 3
  • 20
  • 30