Reputation: 11233
Is there a way to define a constant within a class function?
Example:
class ExampleApp
{
const FORM = TRUE;
public function __construct()
{
switch(Base::color())
{
case 'green':
self::FORM = 'G';
break;
case 'red':
self::FORM = 'R';
break;
default:
self::FORM = 'W';
break;
}
}
public function process() { return TRUE; }
}
The above example code won't work obviously!
From my programming knowledge you can't redefine constants else they would be "constants". But how do you define a costant within a function?! In my example that function being the constructor, or is this entirely not possible?
Upvotes: 0
Views: 4794
Reputation: 2112
By saving it in a property. NOT a static property, just a property with getters and setters.
class ExampleApp
{
const FORM_COLOR_GREEN = "G";
const FORM_COLOR_RED = "R";
const FORM_COLOR_DEFAULT = "W";
private $form_color;
public function getFormColor()
{
return $this->form_color;
}
public function setFormColor( $color )
{
$this->form_color = $color;
}
public function __construct( $color = NULL )
{
switch( $color )
{
case 'green':
$this->setFormColor( self::FORM_COLOR_GREEN );
break;
case 'red':
$this->setFormColor( self::FORM_COLOR_RED );
break;
default:
$this->setFormColor( self::FORM_COLOR_DEFAULT );
break;
}
}
public function process() { return TRUE; }
}
Then you can get the form colour by calling it with $example_app->getFormColor();
Upvotes: 5
Reputation: 7576
I think you wanted a static property, not a constant
public static $form = true;
However, don't put variable name in uppercase letters then, since it's not a constant, not to confuse other developers.
You can asccess it like you did in your methods with self::form
Upvotes: 8