Spex3
    

PHP Variables: Declaration, Scope, and Data Types


    

    

PHP Variables: Declaration, Scope, and Data Types
1. Declaring Variables in PHP
In PHP, variables start with a $ sign.

Variable names are case-sensitive ($name and $Name are different).

Variables do not need explicit type declarations (PHP is loosely typed).

✅ Example:


<?php
$name = "John"; // String
$age = 25; // Integer
$price = 9.99; // Float
$isAdmin = true; // Boolean
?>


2. PHP Variable Scope
Variable scope defines where a variable can be accessed in a script.

Types of Variable Scope:

Scope Description

Local Declared inside a function and accessible only within that function.

Global Declared outside a function and accessible throughout the script.

Static Retains its value even after the function exits.

Superglobal Special variables accessible anywhere (e.g., $_GET, $_POST).

Examples of Scope:

🔹 Local Variable Example


<?php
function myFunction() {
$localVar = "I'm local!";
echo $localVar;
}
myFunction();
// echo $localVar; // ❌ Error: Undefined variable
?>


🔹 Global Variable Example


<?php
$globalVar = "I'm global!";

function showVar() {
global $globalVar; // Using 'global' to access outside variable
echo $globalVar;
}
showVar();
?>


🔹 Static Variable Example

<?php
function counter() {
static $count = 0; // Retains value across function calls
$count++;
echo $count . "
";
}

counter(); // Output: 1
counter(); // Output: 2
counter(); // Output: 3
?>


3. PHP Data Types
PHP supports different data types:

Data Type Example Description

String "Hello, PHP" A sequence of characters.

Integer 42 Whole numbers (positive or negative).

Float 3.14 Numbers with decimal points.

Boolean true or false Represents truth values.

Array ["Apple", "Banana", "Cherry"] Stores multiple values.

Object new ClassName() Represents an instance of a class.

NULL NULL Represents a variable with no value.

4. Data Type Examples
🔹 Strings

<?php
$text = "Hello, PHP!";
echo $text;
?>


🔹 Integers

<?php
$number = 100;
var_dump($number); // Output: int(100)
?>


🔹 Floats


<?php
$pi = 3.14159;
var_dump($pi); // Output: float(3.14159)
?>


🔹 Booleans

<?php
$isPHPFun = true;
var_dump($isPHPFun); // Output: bool(true)
?>

🔹 Arrays


<?php
$fruits = ["Apple", "Banana", "Cherry"];
echo $fruits[0]; // Output: Apple
?>


🔹 Objects



<?php
class Car {
public $brand;
function setBrand($brand) {
$this->brand = $brand;
}
}

$myCar = new Car();
$myCar->setBrand("Toyota");
echo $myCar->brand; // Output: Toyota
?>

🔹 NULL

<?php
$emptyVar = NULL;
var_dump($emptyVar); // Output: NULL
?>




Conclusion
PHP automatically assigns a data type based on the value.

Understanding scope helps avoid variable conflicts.

Arrays and Objects allow storing multiple values effectively.


    Date: 2025-03-28 00:00:00.000000