What is a Variable in PHP?
Imagine a massive e-commerce website. You add an item to your cart, navigate to another page, and when you check out, the item is still there. How does the system "remember" your choice? It uses variables.
Under the hood, variables are like labeled storage boxes in your server's RAM. They allow you to store a piece of information (like a username, a game score, or a product's price), give that "box" a human-readable name, and access or modify its contents at any point while your script is running.
How to Declare Variables (The Dollar Sign Rule)
Unlike languages like JavaScript (which uses let or const) or Python (which uses nothing), PHP has a very strict visual rule: every single variable must start with a dollar sign ($). This makes it incredibly easy to spot data containers inside a large file.
Declaring a variable is as simple as creating it and assigning a value using the equals sign (=).
<?php
// Declaring different types of variables
$customer_name = "John Doe"; // String (Text)
$total_price = 199.90; // Float (Decimal)
$is_logged_in = true; // Boolean (True/False)
?>
Mandatory Naming Rules in PHP
To ensure your code doesn't throw fatal syntax errors, you must respect the PHP engine's strict naming rules:
- The Beginning: After the
$, the name must start with a letter or an underscore (_). It can never start with a number. - Allowed Characters: Variable names can only contain alphanumeric characters and underscores (A-z, 0-9, and _).
- No Spaces: Spaces are strictly forbidden. Use
$full_name(Snake case) or$fullName(Camel case). - Case Sensitivity: PHP treats uppercase and lowercase letters differently.
$User,$user, and$USERare three entirely different variables.
Best Practices: Writing Professional "Clean Code"
While you can legally name your variables $x, $y, or $a1, you should avoid this at all costs. In professional environments, code is read far more often than it is written. Use descriptive names:
- Use
$current_levelinstead of$cl. - Use
$user_balanceinstead of$bal. - Use
$button_colorinstead of$bc.
Dynamic Typing: The Flexibility of PHP
PHP is a dynamically typed language. This means you do not need to tell PHP what type of data you are storing (like you would in C++ or Java). Furthermore, a variable can completely change its data type on the fly during the script's execution:
<?php
$data = "Sarah"; // Currently holds a String
echo "User: " . $data . "<br>";
$data = 25; // The exact same variable now holds an Integer!
echo "Age: " . $data;
?>
Printing Variables: String Interpolation (Single vs. Double Quotes)
A very common task is mixing text (strings) with variables to output dynamic HTML. This is where PHP shines. If you wrap your text in double quotes (" "), PHP will automatically scan the text, find the $, and inject the variable's value. This is called String Interpolation.
If you use single quotes (' '), PHP will print exactly what you typed, ignoring the variable.
<?php
$language = "PHP";
// Using Double Quotes (Interpolation works)
echo "I love learning $language!";
// Output: I love learning PHP!
// Using Single Quotes (Literal string)
echo 'I love learning $language!';
// Output: I love learning $language!
?>
⚠️ Common Error: "Undefined variable"
If you see a PHP Warning saying "Warning: Undefined variable $username", it usually means two things: you either forgot to assign a value to it before using echo, or you made a typo when typing the variable's name (e.g., declaring $userName but trying to echo $username).
Have you run your first PHP script with variables yet? What was the name of your first data container? Let us know in the comments!
What's Next? Time to do some Math!
Now that you have stored data inside variables, it's time to manipulate them. In the next tutorial, we will learn how to build calculators, sum prices, and manipulate data using PHP Arithmetic Operators.
Go to the Next Lesson in the Syllabus →
Nenhum comentário:
Postar um comentário