Showing posts with label PHP CONSTANTS. Show all posts
Showing posts with label PHP CONSTANTS. Show all posts

Monday, 5 August 2019

PHP tutorial: Constant and echo-print statement

Constant  and echo-print statement

Constants:
1) A constant is a name or an identifier for a simple value. It is defined using the define function and it does not start with $ sign
define(“DBNAME”, TECH);
2) A constant value cannot change during the execution of the script. By default, a constant is case-sensitive. By convention, constant identifiers are always uppercase. A constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. If you have defined a constant, it can never be changed or undefined.
3) A constant differ from variable as variable value can be changed across the execution while constant value cannot
4) Constant value are global across the execution.
5) constant value are retrived using constant() function or simlying we can use echo
<?php
echo “DBNAME”;
echo “constant(DBNAME);
?>
6) PHP defined some predefined constants like _LINE_,_FILE_, _CLASS_
Print/echo statement
1) Print /echo does the same job i.e printing the statement on the screen
example
<?php
print “This is php script”;
echo ” This is php script”;
?>
2) It print the variable name in the same manner as given below
<?php
$x=10
print “This is $x”;
echo ” This is $x”;
?>
This is 10
This is 10
3) The behavior with single quotes is different
<?php
$x=10
print ‘This is $x’;
echo “This is $x”;
?>

Tuesday, 11 September 2018

Get a list of all available constants with PHP

PHP has the function get_defined_constants() which allows you to get a list of all the available constants in an array. This post looks at how to use the get_defined_constants() function and example output from it.
The get_defined_constants() function takes one optional parameter, which specifies whether or not to categorise the constants. The default is false, which means an associative array is returned containing the constant name as the key and the constant value as the value. If the categorise parameter is set to true, a multi-dimensional array is returned containing the section names as the index and then a sub array of name-value pairs in the second dimension.
For example:
print_r(get_defined_constants());
will output something like this:
Array
(
    [E_ERROR] => 1
    [E_WARNING] => 2
    [E_PARSE] => 4
    [E_NOTICE] => 8
    [E_STRICT] => 2048
    [E_CORE_ERROR] => 16
    [E_CORE_WARNING] => 32
    [E_COMPILE_ERROR] => 64
    [E_COMPILE_WARNING] => 128
    [E_USER_ERROR] => 256
    [E_USER_WARNING] => 512
    [E_USER_NOTICE] => 1024
    [E_ALL] => 2047
    [TRUE] => 1
    [FALSE] => 
    [NULL] => 
    [ZEND_THREAD_SAFE] => 
    [PHP_VERSION] => 5.1.6
    [PHP_OS] => Linux
    [PHP_SAPI] => apache2handler
    [DEFAULT_INCLUDE_PATH] => .:/usr/share/pear
...
and
print_r(get_defined_constants(true));
will output something like this:
Array
(
    [internal] => Array
        (
            [E_ERROR] => 1
            [E_WARNING] => 2
            ...
        )
    [libxml] => Array
        (
            [LIBXML_VERSION] => 20626
            [LIBXML_DOTTED_VERSION] => 2.6.26
            ...
        )
    [xml] => Array
        (
            [XML_ERROR_NONE] => 0
            [XML_ERROR_NO_MEMORY] => 1
            ...
         )
    ...
)
If you have any user defined constants they will be listed at the end when not categorised, and in a [user] section when categorised.
 

Related posts:

PHP Magic Constants

There are several PHP "magic constants" (or "magical contants") which can be useful for a variety of reasons. These magic constants aren't actually constants at all, but effectively behave like them, although the values change depending on the context.
These are as follows.

__FILE__

__FILE__ is the full path and file name of the file that is being parsed. This can be useful for debugging purposes, and also for determining the absolute path of the current directory when used in conjunction with the dirname()function. For example, if the file that is echoing out __FILE__ is in /var/www/htdocs/example.php, the following would be output:
Example code:
echo __FILE__;

Example output:
/var/www/htdocs/example.php

Example code:
echo dirname(__FILE__);

Example output:
/var/www/htdocs
Note that if the file __FILE__ is used in is an include file, then the value of __FILE__ is the name of the include file, not the script that includes the file.

__DIR__

__DIR__ contains the directory of the file it is in. If the file is an include, it is the directory that include file is in. If it is the main script it is the directory that script is in.
__DIR__ is available from PHP 5.3; unless your application is designed to work only from PHP 5.3 or later, use the more traditional dirname(__FILE__) instead.

__LINE__

__LINE__ is the current line number of the file that is being parsed. This can be useful for debugging purposes.
Note that if the file __LINE__ is used in is an include file, then the value of __LINE__ is the line number of the include file, not the script that includes the file.

__CLASS__

Class is the class name. In PHP5 the value is case-sensitive and will be the exact case matched value of the class name; in PHP4 the value will be in lower case. As the following examples show, __CLASS__ is the class name of the class that it is called in; when calling a method from the parent's class, the parent's class is used.
class foo {
  function bar() {
    echo __CLASS__ . '<br />';
  }
}
class bar extends foo {
  function baz() {
    echo __CLASS__ . '<br />';
  }
}
foo::bar(); // echos 'foo'
bar::bar(); // echos 'foo'
bar::baz(); // echos 'bar'

__METHOD__

__METHOD__ is available from PHP 5.0, and is the name of the current method. It is returned as it was declared so is case sensitive.
class foo {
  function bar() {
    echo __METHOD__ . '<br />';
  }
}

// the example below echos foo::bar
foo::bar(); 

// the example below echos foo::bar
$foo = new foo();
$foo->bar();

__FUNCTION__

__FUNCTION__ is the fuction name of the current function, and works for both class methods and regular functions. In PHP5 the value is case-sensitive and will be the exact case matched value of the function name; in PHP4 the value will be in lower case.
The first example below shows using __FUNCTION__ in a class method; the second from a regular function.
class foo {
  function bar() {
    echo __FUNCTION__ . '<br />';
  }
}

// the example below echos bar
foo::bar();

function bar() {
  echo __FUNCTION__ . '<br />';
}

// the example below echos bar
bar();
The PHP manual reference page for magic constants is at http://www.php.net/manual/en/language.constants.predefined.php

Related posts:

How to tell if a PHP constant has been defined already

You can define constants in PHP with the define() function and can check if a constant has already been defined with the defined() function. This post looks at both functions with some examples.

Defining a constant with PHP

Before showing some examples of checking if a constant has been defined with PHP we'll briefly look at how to define a constant first. This is done with the define() function where the first parameter passed is the name of the constant and the second parameter the value.
The following example sets the constant FOO with the value 'bar'. Constant names do not have to be uppercase but the naming convention means they usually are:
define('FOO', 'bar');
Note the constant name is enclosed with quotes. Without the quotes you are actually passing a constant to the function instead of the name, and will generate a notice type error mesage if that constant has not already been defined like so:
PHP Notice:  Use of undefined constant FOO - assumed 'FOO' in ...
If the constant FOO has not already been defined then it will actually define a constant with the name FOO anyway; this is undesirable behaviour and may have unexpected consequences depending if the constant had already been defined or not, so make sure you always use either single quotes or double quotes when defining the name of the constant.

Notice error if a constant is defined twice

If you attempt to define a constant twice in PHP you will get a notice type error message. The following example attempts to define FOO twice:
define('FOO', 'bar');
define('FOO', 'bar');
And you will get an error message like so:
PHP Notice:  Constant FOO already defined in ...

Checking to see if a constant has been defined with PHP

Checking to see if a function has already been defined in PHP is done using the defined() function which works in a similar way to the define() function. A single parameter is passed in which again needs to be a single or double quoted string.
To test if FOO has been defined and to take appropriate action, you could do something like this:
if(defined('FOO')) {
    // do something when it is defined
}
else {
    // do something else because it isn't
}
To do something only if FOO hasn't been defined you could do this:
if(!defined('FOO')) {
    // do something because it's not defined
}
And finally, to test to see if the constant FOO has been defined and define it if it hasn't, do this:
if(!defined('FOO')) {
    define('FOO', 'bar');
}

Future posts

In next Monday's post I'll look at how to specify a custom error handler for the PHP ADODB Lite database abstraction library. This involves the use of defining appropriate constants and so is a good follow up to this post with a real world example.
Make sure you subscribe to my RSS feed (details below) if you haven't already so you keep up to date with posts on my blog as they are made.

Related posts:

Get the value of a PHP constant dynamically

It is possible to get the value of a PHP constant dynamically using the constant() function. It takes a string value as the parameter and returns the value for the constant if it is defined.

Using PHP's constant() function

In a web application I was working on recently there were a number of constants defined for dealing with country based information, and stored the value of a database ID. For example:
define('SITE_ID_NZ', 1);
define('SITE_ID_AU', 2);
define('SITE_ID_US', 3);
define('SITE_ID_CA', 4);
Elsewhere in the code, the country code only is stored and passed around the place so there needs to be a way to construct the above constants in code to get the database id. Enter the constant() function. This first example would echo the value for the SITE_NZ constant:
$country_code = 'NZ';
// ... some other code in the meantime ...
echo constant('SITE_ID_'.$country_code);
Another approach might be to have the constant value returned by a function:
function get_country_id($country_code) {
    return constant('SITE_ID_'. strtoupper($country_code));
}
Note the use of the strtoupper() function to ensure the country code is upper case. You may or may not need this in your own code depending on the circumstances.
If the constants are defined as part of a class they can also be retrieved using the constant function like so:
class example {

    const SITE_ID_NZ = 1;
    const SITE_ID_AU = 2;
    const SITE_ID_US = 3;
    const SITE_ID_CA = 4;
   
    function get_country_id($country_code) {
        return constant('self::SITE_ID_'.strtoupper($country_code));
    }
   
}

If the constant is not defined

If the constant is not defined then the call to constant() will return null, but it will also issue a warning, resulting in some output like this:
Warning: constant(): Couldn't find constant ... in ... on line ...
Therefore, a test should be done first to check if the constant is actually defined. The function example above would then be modified to look like so:
function get_country_id($country_code) {
    $constant = 'SITE_ID_'.strtoupper($country_code);
    if(defined($constant)) {
        return constant($constant);
    }
    else {
        return false;
    }
}
And the class version would now look like this:
class example {

    const SITE_ID_NZ = 1;
    const SITE_ID_AU = 2;
    const SITE_ID_US = 3;
    const SITE_ID_CA = 4;
   
    function get_country_id($country_code) {
        $constant = 'self::SITE_ID_'.strtoupper($country_code);
        if(defined($constant)) {
            return constant($constant);
        }
        else {
            return false;
        }
    }
   
}

Related posts:

Monday, 2 February 2015

Friday, 19 September 2014

PHP: Constants in PHP

In PHP, you can define names, called constants, for simple values. As the name implies, you cannot change these constants once they represent a certain value. The names for constants have the same rules as PHP variables except that they don’t have the leading dollar sign. It is common practice in many programming languages - including PHP - to use uppercase letters for constant names, although you don’t have to. If you wish, which we do not recommend, you may define your constants as case-insensitive, thus not requiring code to use the correct casing when referring to your constants.
Tip: Only use case-sensitive constants both to be consistent with accepted coding standards and because it is unclear if case-insensitive constants will continued to be supported in future versions of PHP.
Unlike variables, constants, once defined, are globally accessible. You don’t have to (and can’t) redeclare them in each new function and PHP file.
To define a constant, use the following function:
define("CONSTANT_NAME", value [, case_sensitivity])
Where:
. "CONSTANT_NAME" is a string.
. value is any valid PHP expression excluding arrays and objects.
. case_sensitivity is a Boolean (true/false) and is optional. The default is true.
An example for a built-in constant is the Boolean value true, which is registered as case-insensitive.
Here’s a simple example for defining and using a constant:
define("MY_OK", 0);
define("MY_ERROR", 1);
...
if ($error_code == MY_ERROR) {
print("There was an error\n");
}