define

Views: 20 Last modified: August 11th, 2011 Comments: 0

The PHP built in function “define” is available when you want to define a constant. A constant literally means “a value which does not change” or “it will always be there”.

Constants are used to define certain values or maybe servers paths, which will never change or always point to one single direction.

This function takes 3 parameters.

  • The constant name
  • The constant value
  • Case-insensitive (CONSTANT_1 is the same as constant_1)

How do we define a constant ? Simple…. In this example we will define 2 constants “CONSTANT_1″ & “CONSTANT_2″.

<?php
// Define a constant
define('CONSTANT_1', 'value of constant 1');

// Define another constant
define('CONSTANT_2', 'value of constant 2');

// Call constant 1
echo constant('CONSTANT_1');

// Just a line break
echo '<br />';

// Call constant 2
echo CONSTANT_2;
?>

You can call the defined constant with a single “echo”, “print” or return it from a function. All you have to do is type the “constant name”.

The above example will result in….

value of constant 1
value of constant 2

This is quite simple right ?
However, the current constants are case-sensitive, so CONSTANT_1 is not constant_1.

So, the following example will result in a notice about a undefined constant.

<?php
// Define another constant
define('CONSTANT_2', 'value of constant 2');

// Call constant 2
echo constAnt_2;
?>

But, if we add the third parameter (true), it will be treated as the same constant, only case-insensitive (if it matches the full pattern off course). So the following example will work just fine.

<?php
// Define another constant
define('CONSTANT_2', 'value of constant 2', true);

// Call constant 2
echo constAnt_2;
?>

The result…

value of constant 2
VN:F [1.9.13_1145]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.13_1145]
Rating: 0 (from 0 votes)

    Mail this!

    To: From:Sum {4+5} =  
    Anything to add ?

        You must be logged in to post a comment.