Jump to content

[SOLVED] some advice on define()


Dragen

Recommended Posts

Is there any advantage to using define() instead of just setting a variable?

I've not really used define before, but was just wondering what difference it made:

<?php
// What's the difference between this:
define('MY_VARIABLE', 'my value');

// and this:
$myvariable = 'my value';
?>

Link to comment
https://forums.phpfreaks.com/topic/54794-solved-some-advice-on-define/
Share on other sites

Define can be used in any scope, so functions and classes can use define without having to use global.

 

Define's value is CONSTANT meaning it cannot be modified later on the script, where as $myvariable can be.

 

Define is really for configuration variables and the likes of that.

define() defines a CONSTANT , a variable that will never change its value, in your case whenever you call MY_VARIABLE it will always carry the value of 'my value'

 

just creating a variable allows it to be changed whenever a call is made to change it

 

see the <a href="http://uk2.php.net/manual/en/language.constants.php"> manual here </a> for information on constants

I was trying to use some defines but have one issue with it

 

a regular variable i would set up like this

 

$randomStuff = "asdf";

echo "whatever $randomStuff";

 

would output:

whatever asdf

 

However, how would you do this with a define.

 

define("randomStuff", "asdf");

echo "whatever randomStuff";

outputs

whatever randomStuff..

How would I make it output asdf?

you'd need to use this, I think:

define("randomStuff", "asdf");
echo "whatever " . randomStuff;

 

Thanks for the advice guys!

 

That is right, but as a general rule of thumb, all constants should be capital.

 

define("RANDOM_STUFF", "asdf");
echo "whatever " . RANDOM_STUFF;

 

That way incase someone tries to help you out, they do not think it is an error of leaving out the $ for the variable etc. It is good to follow the generic guidelines.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.