declaration
In PHP, declaring variables and constants follows specific syntax and rules. Here's an overview of the various declarations you can perform in PHP:
Variable Declaration
Variables in PHP are declared by assigning a value to a variable name prefixed with a dollar sign ($). PHP is a loosely typed language, so you don't need to declare the type of the variable explicitly.
<?php
// String variable
$name = "John Doe";
// Integer variable
$age = 30;
// Float variable
$height = 5.9;
// Boolean variable
$is_student = true;
// Array variable
$colors = array("red", "green", "blue");
// Associative array variable
$user = array("name" => "Jane Doe", "age" => 25);
// Null variable
$unknown = null;
?>
Constant Declaration
Constants are declared using the define() function or the const keyword. Constants are case-sensitive by default and cannot be changed once they are set.
Using define()
<?php
define("SITE_NAME", "My Website");
define("MAX_USERS", 100);
// Accessing constants
echo SITE_NAME; // Outputs "My Website"
echo MAX_USERS; // Outputs 100
?>
Using const
<?php
const SITE_URL = "https://www.example.com";
const TIMEOUT = 30;
// Accessing constants
echo SITE_URL; // Outputs "https://www.example.com"
echo TIMEOUT; // Outputs 30
?>
Declaring Constants in Classes
Constants can also be declared within classes.
<?php
class MyClass {
const CONSTANT_VALUE = 'A constant value';
public function showConstant() {
echo self::CONSTANT_VALUE;
}
}
// Accessing class constants
echo MyClass::CONSTANT_VALUE; // Outputs "A constant value"
$myObject = new MyClass();
$myObject->showConstant(); // Outputs "A constant value"
?>
Type Declarations
From PHP 7 onwards, you can specify the type of function arguments, return values, and properties.
Function Argument Type Declarations
<?php
function addNumbers(int $a, int $b): int {
return $a + $b;
}
echo addNumbers(5, 10); // Outputs 15
?>
Return Type Declarations
<?php
function getGreeting(): string {
return "Hello, World!";
}
echo getGreeting(); // Outputs "Hello, World!"
?>
Nullable Type Declarations
You can allow a function argument or return type to be null by prefixing the type with a question mark (?).
<?php
function setAge(?int $age) {
if (is_null($age)) {
echo "Age is not provided.";
} else {
echo "Age is $age.";
}
}
setAge(25); // Outputs "Age is 25."
setAge(null); // Outputs "Age is not provided."
?>
Class Property Type Declarations (PHP 7.4+)
<?php
class Person {
public string $name;
public int $age;
public function __construct(string $name, int $age) {
$this->name = $name;
$this->age = $age;
}
}
$person = new Person("Alice", 30);
echo $person->name; // Outputs "Alice"
echo $person->age; // Outputs 30
?>
These examples cover various declarations in PHP, demonstrating how to declare and use variables, constants, and type hints in functions and classes.