Page 1 of 1

Possible PHP Bug With const?

Posted: Mon Oct 19, 2009 11:24 am
by jackpf
Hi,

I don't know if this is supposed to happen or not...but check this out:

Code: Select all

<?php
define('one', 1); // one will be 1
const two = 2; // two will be 2 (as of php 5.3)
 
define('one_or_two', 1 | 2); // one_or_two will be 3
const two_or_three = 2 | 3; // error
?>
This is quite annoying, because I need to use the or operator in one of my class constants. I could just add the values up...but this makes more sense - next time I go back to look over my code, instead of seeing a random number and wondering what it's for, I'll see the comparison.

So yeah, has anyone ever come across something similar, or even better, know a way to fix it? :?

Thanks, Jack.

Re: Possible PHP Bug With const?

Posted: Mon Oct 19, 2009 12:35 pm
by AbraCadaver
What do you want to happen? Performing a bitwise OR (1 | 2) is 3. If you need to use the expression 1 | 2 then it needs to be a string:

define('one_or_two', '1 | 2');

-Shawn

Re: Possible PHP Bug With const?

Posted: Mon Oct 19, 2009 3:26 pm
by jackpf
I think you misunderstand.

define() works fine. It's using "const" that doesn't.

If you test out my script, you'll see what I mean.

I don't see how using a string will work :/

Cheers,
Jack.

Re: Possible PHP Bug With const?

Posted: Mon Oct 19, 2009 3:40 pm
by AbraCadaver
For const http://us.php.net/manual/en/language.oop5.constants.php: The value must be a constant expression, not (for example) a variable, a property, a result of a mathematical operation, or a function call.

This is not the case for define().

Re: Possible PHP Bug With const?

Posted: Mon Oct 19, 2009 3:43 pm
by jackpf
Oh right.

That's stupid :/

Oh well. Thanks for pointing that out AbraCadaver.

Re: Possible PHP Bug With const?

Posted: Mon Oct 19, 2009 3:58 pm
by AbraCadaver
Yeah, it is inconvenient that they would treat them differently, but classes, class constants and functions are declared compile time, so they can have only constant values. Global constants declared with define() are declared runtime so they can take the result of an expression.