Chapter 5: What are Variables?

Definition

A variable is a named container that holds a value. Think of it like a labeled box where you can store information and retrieve it later. You can also change what's inside the box.

In HolyPHP (and PHP), variables always start with a dollar sign $.

Creating Variables

To create a variable, just assign a value to it using the = operator:

$name = "Alice";
$age = 25;
$pi = 3.14159;

You don't need to declare the variable type first - HolyPHP will figure it out automatically based on the value you assign. This is called type inference.

Using Variables

$name = "Bob";
echo "My name is " . $name;

// Or use string interpolation
echo "My name is {$name}";

Both work, but string interpolation with {$variable} is often cleaner and more readable.

Variable Naming Rules

Valid names:

$firstName = "John";
$_count = 10;
$user_id = 123;

Invalid names:

$1name = "John";    // Can't start with number
$first name = "John"; // No spaces
$first-name = "John"; // Hyphens not allowed

Reassigning Variables

You can change the value of a variable anytime:

$x = 5;
echo $x; // Outputs: 5

$x = 10;
echo $x; // Outputs: 10

$x = "hello";
echo $x; // Outputs: hello

Notice that in HolyPHP, a variable can change its type when reassigned (unlike languages with strict static typing). This is flexible like PHP!

Variable Scope (Intro)

For now, just know that variables defined in your main program are available throughout. We'll learn more about scope in functions later.

Good Practice: Use descriptive variable names. $userAge is better than $ua - your future self will thank you!
Challenge: Create variables for a person (name, age, city, isStudent), assign values, and print them using string interpolation.