Jump to content

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.