Variables Types in PHP

Types of Variables

In PHP, variables can hold values of various types.

String :

Variables that hold text or character data. Strings can be enclosed in single quotes (') or double quotes (")

				
					$name = "John";
				
			

Integer :

Variables that store whole numbers (positive or negative) without decimal points

				
					$age = 30;
				
			

Float (Floating-Point Number) :

Variables that store numbers with decimal points

				
					$age = 30;
				
			

Boolean :

Variables that hold either true or false to represent a binary state

				
					$is_active = true;
				
			

Array :

Variables that can hold multiple values in an ordered list. PHP supports both indexed and associative arrays

				
					$colors = ["red", "green", "blue"];
$person = ["first_name" => "John", "last_name" => "Doe"];

				
			

Object :

Variables that can hold instances of user-defined classes or built-in PHP classes (e.g., DateTime)

				
					class Person {
    public $name;
    public $age;
}
$person = new Person();
$person->name = "Alice";
$person->age = 25;
				
			

Null :

Variables that have no value or represent the absence of a value

				
					$no_value = null;
				
			

Resource :

Variables that hold references to external resources like database connections or file handles. These are typically managed internally by PHP and are not commonly used directly in user code

				
					//file handling
$fileHandle = fopen("example.txt", "r");
// database
$mysqli = new mysqli("localhost", "username", "password", "database");
				
			

Callable :

Variables that can hold references to functions or methods, allowing you to call them dynamically.
its like storing anonymous function into a variable.

				
					$my_function = function($arg) {
    return "Hello, $arg!";
};
// call function variable and pass a argument with it simple function call
echo $my_function("World"); // Outputs: Hello, World!
				
			

Variable Variables :

These are variables that can hold variable names as their values. This allows you to dynamically create and manipulate variable names

				
					$var_name = "count";
$$var_name = 42; // Creates a variable $count with a value of 42
echo $count; // Outputs: 42
				
			
Posted Under PHP

Leave a Reply

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