Data Types and Constants

PHP Data Types


PHP data types are used to hold different types of data or values. PHP supports 8 primitive data types that can be categorized further in 3 types:

  1. Scalar Types (predefined)
  2. Compound Types (user-defined)
  3. Special Types

 

PHP Data Types: Scalar Types

It holds only single value. There are 4 scalar data types in PHP.

  1. boolean
  2. integer
  3. float
  4. string

 

PHP Data Types: Compound Types

It can hold multiple values. There are 2 compound data types in PHP.

  1. array
  2. object

 

PHP Data Types: Special Types

There are 2 special data types in PHP.

  1. resource
  2. NULL

 

PHP Constants


 

PHP constants are name or identifier that can’t be changed during the execution of the script except for magic constants, which are not really constants. PHP constants can be defined by 2 ways:

  1. Using define() function
  2. Using const keyword

Constants are similar to the variable except once they defined, they can never be undefined or changed. They remain constant across the entire program. PHP constants follow the same PHP variable rules. For example, it can be started with a letter or underscore only.

 

PHP constant: define()

Use the define() function to create a constant. It defines constant at run time. Let’s see the syntax of define() function in PHP.

Syntax

 define(name, value, case-insensitive)

Constant() function

There is another way to print the value of constants using constant() function instead of using the echo statement.

Syntax

constant (name)

PHP Variables Scope


In PHP variables can be declared anywhere in the script.

The scope of a variable is the part of the script where the variable can be referenced/used.

PHP has three different variable scopes:

  • local
  • global
  • static

 

Global variable

The global variables are the variables that are declared outside the function. These variables can be accessed anywhere in the program. To access the global variable within a function, use the GLOBAL keyword before the variable. However, these variables can be directly accessed or used outside the function without any keyword. Therefore there is no need to use any keyword to access a global variable outside the function.

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *