Declare class variable: number


I know this is usually not a good practice, but I’m trying to declare a variable named “302”, and it really makes sense in the context of my class.

protected ${"302"};

This obviously doesn’t work. I’ve tried a few combinations, without success.

Anyone knows how to do it?


-jj. :slight_smile:

You dont. Variables in PHP must start with either a letter or an underscore.

I was poking around with const and define() and I discovered this:

define("302", "My 302 message");

echo 302 . PHP_EOL;

if( defined("302") ) { 
echo 'well it is defined ... somewhere at least... ' .PHP_EOL ;
echo constant("302") . PHP_EOL;


well it is defined … somewhere at least…
My 302 message

But I cannot replicate it in a class using const, you have to precede it with a letter or _ etc.

How are these representations in you class so useful? Doing redirects?

echo 302 . PHP_EOL;

Wouldnt that fail because of the concatenation operator casting the 302 as a string to concatenate it to "
" (or whatever PHP_EOL evaluates to)?

It did. It cast the constant 302 by variable name to “302” and appended the PHP_EOL to the end.

I agree with everything stated at this point, that your best bet is using _302 and using getters and setters to work with the value.

public function Get302()
  return $this->_302;

public function Set302($value)
  // do any validation that may be necessary
  $this->_302 = $value;

This at least makes it a bit more readable and easier to remember how to access the variable from a development standpoint.

echo 302;

without the PHP_EOL still outputs 302 … so somehow it seems its’ abject inability to follow the rules of constant or variable definition therefore cause it not be looked up in the variables table – even though it somehow circumvented those rules to get itself added into that table.

Is there are rational explanation? If so I’d like to hear it.

Whether anyone finds it remarkable, odd, or quirky – its such an edge case, does it really matter? Probably not.

Anyhow, I’m still left wondering how the OPs class is using (or intending to use) these vars …