Why use constants?
Moderator: General Moderators
Why use constants?
What is the point of constants? What advantages to they give me? Why would I use them?
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.
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";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";
- Chris Corbyn
- Breakbeat Nuttzer
- Posts: 13098
- Joined: Wed Mar 24, 2004 7:57 am
- Location: Melbourne, Australia
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);
}
}-
Jeroen Oosterlaar
- Forum Commoner
- Posts: 37
- Joined: Sun Nov 06, 2005 4:12 pm
I think it is just a matter of definition. When I write a configuration file, it feels logical to define constants as... constants, such as the database host address, username, password etc. I could just as well define such properties as variables, because I know that they will not be changed by other routines, but with respect to the beauty of the design, using constants is preferable.
Constants are also handy because they are similar to superglobals in that they can be accessed anywhere, by any scope.
e.g.
e.g.
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;
}
}
?>- Chris Corbyn
- Breakbeat Nuttzer
- Posts: 13098
- Joined: Wed Mar 24, 2004 7:57 am
- Location: Melbourne, Australia