Why use constants?
Posted: Wed Nov 09, 2005 2:43 pm
What is the point of constants? What advantages to they give me? Why would I use them?
A community of PHP developers offering assistance, advice, discussion, and friendship.
http://forums.devnetwork.net/
Things like configuration/language constants are popular examples of this. Basically, stuff you don't want anybody/anything to change during page execution, just to make sure you or someone else doesn't screw it up by accident.One armed space goat wrote:Anybody have any examples of why anybody would need them?
One armed space goat wrote:So, can you define constants any other way than define()?
Nothing else is said.The [url=http://php.net/language.constants]PHP Manual[/url] wrote: You can define a constant by using the define()-function.
Code: Select all
CONSTANT = "something";Try. It.One armed space goat wrote:I read that part... that's how I know you can do it that way... is there any other way to do it? ie:Code: Select all
CONSTANT = "something";
Depends if we're talking OOP or proceduralOne armed space goat wrote:I read that part... that's how I know you can do it that way... is there any other way to do it? ie:Code: Select all
CONSTANT = "something";
Code: Select all
class foo
{
const color = 'red'; //Accessed by self::color
const flavor = 'tomato'; // self::flavor
private $private_property; // $this->private_property (read/write only inside this class)
public $public_property = 'default_value'; // $this->public_property (read/write anywhere)
public function dump()
{
print_r($this);
}
}Code: Select all
<?php
define('MYCONST', 10);
//within same scope..
echo MYCONST;
function myFunc()
{
//within a function..
echo MYCONST;
}
class myClass
{
//within a class
var $myVar = MYCONST;
function myFunc()
{
//within a method..
echo MYCONST;
}
}
?>